[{"content":"Open Source Github: https://github.com/seth-shi/apple-refund-assistant Overview This service is built on Laravel / Filament multi-tenant architecture, effectively helping developers prevent fraudulent refunds by instantly processing Apple\u0026rsquo;s CONSUMPTION_REQUEST notifications and asynchronously returning consumption data.\nMulti-tenant Support Multi-language Support (中文 / English / Español / हिन्दी / العربية / Português / Русский / 日本語 / Français) Multi-currency Support Zero Dependency File+SQLite or upgrade to Redis+MySQL 100% Test Coverage Self-hosted App Keys Private keys are only stored in your database apps table (symmetric encryption, key generated by your application) 12 Consumption Fields - Calculate all required Apple fields Notification Message Forwarding Apple servers send to current service, current service forwards to your production server Online Demo 🌐 Demo URL: https://apple-refund-assistant.shiguopeng.cn/\n⚠️ Note: The system resets every 30 minutes.\nScreenshots Dashboard Overview Application Management Transaction Details Refund Processing Multi-language Support Settings Configuration Quick Start Using Pre-built Image docker run -d \\ -p 8080:8080 \\ --name apple-refund-assistant \\ --restart=always \\ ghcr.io/seth-shi/apple-refund-assistant:latest Local Build and Run git clone https://github.com/seth-shi/apple-refund-assistant cd apple-refund-assistant ## Build image and deploy ./deploy.sh If you need to mount data touch database.sqlite docker run -d \\ -p 8080:8080 \\ -v $(pwd)/database.sqlite:/var/www/html/database/database.sqlite \\ --name apple-refund-assistant \\ --restart=always \\ ghcr.io/seth-shi/apple-refund-assistant:latest Consumption Field Strategy Documentation: https://developer.apple.com/documentation/appstoreserverapi/consumptionrequest Strategy Code: ConsumptionService.php users table fields can be updated by other systems Field Description Data Table Source Calculation Rule accountTenure User registration days users.register_at Current time minus registration time appAccountToken Account token users.app_account_token Needs to be passed by client when creating orders consumptionStatus Consumption status transactions.expiration_date Compare with current time, if expired return consumed customerConsented User consent to provide data None Hardcoded true deliveryStatus Whether successfully delivered a functional in-app purchase. None Hardcoded 0(normal delivery) lifetimeDollarsPurchased Total in-app purchase amount users.purchased_dollars Accumulate this field based on Apple transaction events, you can also accumulate manually lifetimeDollarsRefunded Total refund amount users.refunded_dollars Accumulate this field based on Apple refund events, you can also accumulate manually platform Platform None Hardcoded 1(apple) playTime Value of customer app usage time users.play_seconds Your system needs to support updating this field, otherwise it\u0026rsquo;s 0 refundPreference Expected result of refund request transactions.expiration_date Compare with current time, if expired hope to reject refund sampleContentProvided Whether trial is provided apps.sample_content_provided Configure app when creating application userStatus User status None Hardcoded 1(normal user) Future Plans Have other ideas or interested in collaboration? Please submit an issue on GitHub - we look forward to your feedback! Acknowledgments Rates By Exchange Rate API https://github.com/argus-sight/refund-swatter-lite ","date":"2025-10-08T13:36:17+08:00","image":"https://sethix.com/posts/2025100813-en/cover_hu103dc5672036e37da9675df49b552452_181818_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2025100813-en/","title":"A Zero-Dependency, Multi-Language, Multi-Currency, Multi-Tenant Apple Refund Management Assistant"},{"content":"Preface First of all, Hugo cannot achieve automatic redirection because it is essentially a static site generator. https://discourse.gohugo.io/t/auto-detect-browser-preferred-language/8391 Implementation The theme I\u0026rsquo;m using is https://github.com/CaiJimmy/hugo-theme-stack. Others can be modified as needed. Add language configuration in config.toml: languages: zh-cn: languageName: Chinese weight: 1 en: languageName: English title: \u0026#34;seth-shi\u0026#34; weight: 2 add a switch language button layouts/partials/sidebar/left.html \u0026lt;li id=\u0026#34;lang-switcher\u0026#34;\u0026gt; {{ range .Site.Languages }} \u0026lt;a data-url=\u0026#34;{{ .Lang | relURL }}\u0026#34; href=\u0026#34;javascript:void(0);\u0026#34; class=\u0026#34;lang-item {{ if eq .Lang $.Site.Language.Lang }}active{{ end }}\u0026#34; \u0026gt; {{ .LanguageName }} \u0026lt;/a\u0026gt; {{ end }} \u0026lt;/li\u0026gt; add js script(It is used to automatically jump to the corresponding language homepage based on the language selected by the user) \u0026lt;script const langOptions = {{ .Site.Languages }}.map(l =\u0026gt; l.Lang) const langStoreKey = \u0026#39;__lang__\u0026#39;; const defaultLang = \u0026#39;zh\u0026#39;; const homePages = langOptions.map(l =\u0026gt; `/${l}`).concat(\u0026#39;/\u0026#39;); document.addEventListener(\u0026#39;DOMContentLoaded\u0026#39;, function() { initLangHomePage(); listenLangSwitchEvent() }); function listenLangSwitchEvent() { const currentLang = localStorage.getItem(langStoreKey); const currentPathList = window.location.pathname.split(\u0026#39;/\u0026#39;).filter(v =\u0026gt; v.length \u0026gt; 0); document.querySelectorAll(\u0026#39;#lang-switcher a\u0026#39;).forEach(link =\u0026gt; { link.onclick = function() { let lang = this.getAttribute(\u0026#39;data-url\u0026#39;).replace(\u0026#39;/\u0026#39;, \u0026#39;\u0026#39;); localStorage.setItem(langStoreKey, lang); // /{currentLang?}/posts/xxx =\u0026gt; /{lang?}/posts/xxx const langRedirectPathList = Array.from(currentPathList); if (langOptions.includes(langRedirectPathList[0])) { langRedirectPathList[0] = lang; } else { langRedirectPathList.unshift(lang); } if (langRedirectPathList[0].includes(defaultLang)) { langRedirectPathList.shift(); } langRedirectPathList.unshift(\u0026#39;\u0026#39;); langRedirectPathList.push(\u0026#39;\u0026#39;); window.location.href = langRedirectPathList.join(\u0026#39;/\u0026#39;); }; }); } function initLangHomePage() { const currentPath = window.location.pathname; if (! homePages.includes(currentPath)) { return; } const redirectPath = getInitRedirectPath(\u0026#39;zh\u0026#39;) console.log(`redirect:${redirectPath}`); if (redirectPath !== currentPath) { window.location.href = redirectPath; } } function getInitRedirectPath() { let lang = localStorage.getItem(langStoreKey); if (lang === null) { // from default browser language lang = navigator.language.substring(0, 2); } let mapLang = langOptions[0]; const index = langOptions.findIndex(l =\u0026gt; l.includes(lang)) if (index \u0026gt;= 0) { mapLang = langOptions[index]; } let redirectPath = `/${mapLang}`; if (mapLang.includes(defaultLang)) { redirectPath = \u0026#39;/\u0026#39;; } return redirectPath; } \u0026lt;/script\u0026gt; Translate content The corresponding categories, labels, and contents can be named according to the rules (for example, \u0026lsquo;index.md\u0026rsquo;, copy a file and name it \u0026lsquo;index.en.md\u0026rsquo;). For now, GPT will automatically translate all the content on my blog \u0026lt;?php $rootDir = __DIR__ . \u0026#39;/content/posts\u0026#39;; $dir = opendir($rootDir); $postsDir = []; while (($filename = readdir($dir)) !== false) { if ($filename !== \u0026#34;.\u0026#34; \u0026amp;\u0026amp; $filename !== \u0026#34;..\u0026#34;) { $postsDir[] = $filename ; } } info(sprintf(\u0026#34;total dir: %d\u0026#34;, count($postsDir))); foreach ($postsDir as $i =\u0026gt; $dir) { $index = \u0026#34;{$rootDir}/$dir/index.md\u0026#34;; $enIndex = \u0026#34;{$rootDir}/$dir/index.en.md\u0026#34;; if (! file_exists($index)) { info(\u0026#34;error {$index}\u0026#34;); continue; } if (file_exists($enIndex)) { info(\u0026#34;exists {$enIndex} skip\u0026#34;); continue; } $content = file_get_contents($index); $res = chat($content); $len = strlen($res); if ($len \u0026gt; 0) { file_put_contents($content, $enIndex); } info(\u0026#34;{$i} success [{$len}]{$enIndex} skip\u0026#34;); } function info($msg) { echo $msg . PHP_EOL; } function chat($content, $model = \u0026#39;gpt-40\u0026#39;) { $apiKey = \u0026#34;YOUR_OPENAI_API_KEY\u0026#34;; $endpoint = \u0026#39;https://api.openai.com/v1/chat/completions\u0026#39;; $data = [ \u0026#34;messages\u0026#34; =\u0026gt; [ [\u0026#34;role\u0026#34; =\u0026gt; \u0026#34;system\u0026#34;, \u0026#34;content\u0026#34; =\u0026gt; \u0026#34;According to the hugo format, translate the title, description, tags and content of the file into English. When encountering professional terms or those in English, skip these keywords\u0026#34;], [\u0026#34;role\u0026#34; =\u0026gt; \u0026#34;user\u0026#34;, \u0026#34;content\u0026#34; =\u0026gt; $content] ], \u0026#34;model\u0026#34; =\u0026gt; $model, ]; $headers = array( \u0026#39;Content-Type: application/json\u0026#39;, \u0026#39;Authorization: Bearer \u0026#39; . $apiKey ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data,JSON_UNESCAPED_UNICODE)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); curl_close($ch); $decodedResponse = json_decode($response, true); $ret = \u0026#39;\u0026#39;; if (isset($decodedResponse[\u0026#39;choices\u0026#39;][0][\u0026#39;message\u0026#39;][\u0026#39;content\u0026#39;])) { $ret = $decodedResponse[\u0026#39;choices\u0026#39;][0][\u0026#39;message\u0026#39;][\u0026#39;content\u0026#39;]; } return $ret; } Achievement Multilingual Switch Effect ","date":"2025-04-24T10:42:53+08:00","image":"https://sethix.com/posts/2025042410/cover_hu0f2413c25254d54a58754972261e2512_158850_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2025042410/","title":"Make Your Hugo Blog Multilingual"},{"content":" When working on a Python project recently, I needed to call C++ dynamic library files. Both Python\u0026rsquo;s built-in ctypes library and the pybind11 library can interface with dynamic libraries. ctypes Use ctypes for simple data types - it\u0026rsquo;s preinstalled with Python and straightforward to use However, when dealing with C++ complex types like vector, it throws Segmentation fault (core dumped) errors because ctypes lacks native support for vector type mapping Reference: https://stackoverflow.com/questions/49744870/passing-vector-from-a-c-dll-in-python-ctypes pybind11 pybind11 is a library that compiles C++ code into Python-compatible dynamic libraries: https://github.com/pybind/pybind11 Have C++ colleagues build the .so file and share just that file Key considerations: Ensure build environment Python version matches runtime environment Generated filename format: xxxx.cpython-311(version)-x86_64(architecture)-linux-gnu(OS).so Place the file in project directory, e.g., app/libs/xxx/xxxx.so Execute export PYTHONPATH=\u0026quot;$PYTHONPATH:/var/www/app/libs/xxx\u0026quot; (prevents ModuleNotFoundError: No module named xxx) Type Hinting Install stub generator: pip install pybind11-stubgen Generate stubs in the .so directory: pybind11-stubgen xxx -o . Import and use the generated stubs for type hinting in other modules ","date":"2025-03-28T21:31:03+08:00","image":"https://sethix.com/posts/2025032821/cover_huf677aec3c7cf1514b151e0f9c71265cc_219781_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2025032821/","title":"Calling C++ Dynamic Libraries in Python"},{"content":"Deep Dive into MP4 File Structure When metadata is at the beginning, [mdat] and [moov] swap positions +---------------------------------------------------------------+ | MP4 File Structure | | | | +--------+ +--------+ +--------+ | | | [ftyp] | ------\u0026gt; | [mdat] | ------\u0026gt; | [moov] | | | +--------+ +--------+ +--------+ | | File Type Box Media Data Metadata Container | | | | | +---------------------+ | | | | | +--------------------------------------------------+ | | | [moov] | | | | +-----------------------------+ | | | | | [mvhd] | | | | | +-----------------------------+ | | | | Movie Header Box | | | | | | | | +-----------------------------+ | | | | | [trak] | | | | | +-----------------------------+ | | | | Track Container | | | | / \\ | | | | / \\ | | | | +-------------+ +-------------+ | | | | | [tkhd] | | [mdia] | | | | | +-------------+ +-------------+ | | | | Track Header Media Box | | | | | | | | | | | | | | +------------------+ | | | | | [minf] | | | | | +------------------+ | | | | Media Info Box | | | | / \\ | | | | / \\ | | | | +-------------+ +-------------+ | | | | | [vmhd/smhd] | | [stbl] | | | | | +-------------+ +-------------+ | | | | Video/Audio Box Sample Table | | | | | | | | | +------------------+ | | | | | | | | | | | +-------------+ | | | | | | | [stsd] | | | | | | | +-------------+ | | | | | | Sample Desc. | | | | | | | | | | | | +-------------+ | | | | | | | [stts] | | | | | | | +-------------+ | | | | | | Time-to-Sample | | | | | | | | | | | | +-------------+ | | | | | | | [stss] | | | | | | | +-------------+ | | | | | | Sync Sample | | | | | | | | | | | | +-------------+ | | | | | | | [stsz] | | | | | | | +-------------+ | | | | | | Sample Size | | | | | +------------------+ | | | +--------------------------------------------------+ | | | +---------------------------------------------------------------+ HTTP Range Request Mechanism Explained The HTTP Range request is a crucial feature in HTTP/1.1 protocol that enables partial content retrieval, particularly important for streaming large media files like videos.\nRange Header Syntax Range: bytes=\u0026lt;start\u0026gt;-\u0026lt;end\u0026gt; Video Playback with HTTP-Range Support 1. Initial GET Request (with range) Chrome Server +----------------------------+ +--------------------------------------------------+ | GET /video.mp4 HTTP/1.1 | | HTTP/1.1 206 Partial Content | | Host: cdn.com | \u0026lt;--------\u0026gt; | Accept-Ranges: bytes | | Range: bytes=0- | | Content-Range: bytes 0-11799707/828908176 | +--------------------------+ | Content-Length: 827040401 | | (body: .........) | +--------------------------------------------------+ 2. Seek Operation During Playback Chrome Server +--------------------------------+ +-----------------------------------------------------+ | GET /a.mp4 HTTP/1.1 | \u0026lt;--------\u0026gt; | HTTP/1.1 206 Partial Content | | Host: cdn.com | | Accept-Ranges: bytes | | Range: bytes=1867776-828908176 | | Content-Range: bytes 1867776-828908176/828908177 | +--------------------------------+ | Content-Length: 827040400 | | (body: .........) | +-----------------------------------------------------+ Video Playback Without HTTP-Range Support GET requests enable streaming playback without seek functionality Servers must configure Accept-Ranges: none or omit the header Browsers fall back to linear playback mode when Range isn\u0026rsquo;t supported Metadata Positioning Impact moov box placement in MP4 files significantly affects playback: Front-positioned metadata (faststart): Immediate access to critical video information Enables playback without full file download Supports random seek operations End-positioned metadata: Requires full download or Range requests for metadata retrieval Previews unavailable before metadata acquisition Impacts UX for large files Video Generation Testing ## Metadata at start ffmpeg -f lavfi -i testsrc=duration=60:size=1920x1080:rate=30 -c:v libx264 -c:a aac -movflags +faststart meta_at_start.mp4 ## Metadata at end ffmpeg -f lavfi -i testsrc=duration=60:size=1920x1080:rate=30 -c:v libx264 -c:a aac -movflags empty_moov+default_base_moof meta_at_end.mp4 Test Results Test Results Table order matches image sequence Video File Description Playback Behavior meta_at_start.mp4 Front metadata Immediate playback, no seeking (streaming only) meta_at_end.mp4 End metadata Immediate playback, no seeking (shows 0:08 duration error) meta_at_start_with_range.mp4 Front metadata + range Full playback control with seeking meta_at_end_with_range.mp4 End metadata + range Requires complete download for playback control HLS and M3U8 Streaming Technology Beyond HTTP Range-based streaming, HTTP Live Streaming (HLS) using M3U8 playlists offers alternative media delivery:\nHLS Specification (RFC 8216) +--------------------------------------------------------------------------------------+ | M3U8 File Structure | | | | Master Playlist (master.m3u8) | | +--------------------------------------------------------------------------------+ | | | #EXTM3U | | | | #EXT-X-VERSION:3 | | | | #EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=1920x1080 | | | | stream_0.m3u8 | | | | #EXT-X-STREAM-INF:BANDWIDTH=3000000,RESOLUTION=1280x720 | | | | stream_1.m3u8 | | | | #EXT-X-STREAM-INF:BANDWIDTH=1000000,RESOLUTION=640x360 | | | | stream_2.m3u8 | | | +--------------------------------------------------------------------------------+ | | | | | +-------------+-------------------------------------------+ | | | | | | | v v v | | +------------------------+ +------------------------+ +------------------------+ | | | HD Playlist | | SD Playlist | | LD Playlist | | | | stream_0.m3u8 | | stream_1.m3u8 | | stream_2.m3u8 | | | | | | | | | | | | #EXTM3U | | #EXTM3U | | #EXTM3U | | | | #EXT-X-VERSION:3 | | #EXT-X-VERSION:3 | | #EXT-X-VERSION:3 | | | | #EXT-X-TARGETDURATION:6| | #EXT-X-TARGETDURATION:6| | #EXT-X-TARGETDURATION:6| | | | #EXT-X-MEDIA-SEQUENCE:0| | #EXT-X-MEDIA-SEQUENCE:0| | #EXT-X-MEDIA-SEQUENCE:0| | | | #EXTINF:6.0, | | #EXTINF:6.0, | | #EXTINF:6.0, | | | | data000.ts | | data000.ts | | data000.ts | | | | #EXTINF:6.0, | | #EXTINF:6.0, | | #EXTINF:6.0, | | | | data001.ts | | data001.ts | | data001.ts | | | | ... | | ... | | ... | | | | #EXT-X-ENDLIST | | #EXT-X-ENDLIST | | #EXT-X-ENDLIST | | | +------------------------+ +------------------------+ +--------------------+ | | | | | | | v v v | | +------------+ +------------+ +------------+ | | | HD Segments | | SD Segments | | LD Segments | | | | data000.ts | | data000.ts | | data000.ts | | | | data001.ts | | data001.ts | | data001.ts | | | | ... | | ... | | ... | | | +------------+ +------------+ +------------+ | | | +----------------------------------------------------------------------------------------+ Video Segmentation: Split video into small .ts files\nTypical segment duration: 6-10 seconds Balance between latency and bandwidth adaptation Index File Creation: Generate .m3u8 with segment metadata\nMaster Playlist: Multi-bitrate manifest Media Playlist: Per-quality segment list Adaptive Bitrate: Multiple quality versions\nHD (1080p): 5Mbps bandwidth SD (720p): 3Mbps bandwidth LD (360p): 1Mbps bandwidth Client Workflow: Dynamic quality switching\nNetwork monitoring Seamless quality transitions Comparison with HTTP Range Aspect HLS (M3U8) HTTP Range Format Segmented .ts files Single MP4 file Pros • Adaptive bitrate\n• Broad compatibility\n• Native live support • Low latency\n• Storage efficiency\n• Precise seeking Cons • Higher latency\n• Storage overhead • No ABR\n• Limited compatibility Use Cases • Live streaming\n• Multi-device • VOD\n• Low-latency needs Complexity High (transcoding system) Low (server support) References Http Range Request and MP4 Video Play in Browser HTTP range requests ","date":"2025-03-14T16:05:31+08:00","image":"https://sethix.com/posts/2025031416/cover_hud1fabdecbf5eb637a7fcd6f6f9b3d3cf_232548_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2025031416/","title":"In-Depth Understanding of HTTP Range and Video Streaming Mechanisms"},{"content":" The operations team reported recurring OOM (Out-Of-Memory) restarts in a container pod. Monitoring data showed periodic memory spikes: 1.png The service in question handles video composition via queue jobs. It uses shell_exec to invoke commands like ffmpeg and spleeter for audio processing and quality adjustments.\nSince external command execution isn\u0026rsquo;t trackable through PHP\u0026rsquo;s memory monitoring, we used atop for detailed logging.\nService Setup ## Installation apt update \u0026amp;\u0026amp; apt install -y atop ## Modify the configuration file cat /etc/default/atop LOGOPTS=\u0026#34;\u0026#34; LOGINTERVAL=1 # Set to 1s for granular monitoring LOGGENERATIONS=28 # Retain logs for 28 days LOGPATH=/var/log/atop ## Start service systemctl start atop Diagnosis Process Alibaba Cloud monitoring showed a memory spike at 16:20:30: img.png Investigate historical records using atop:\n## View logs sorted by memory usage atop -m -r ## Press \u0026#39;b\u0026#39; and enter timestamp 1620 b 1620 ## Navigate with \u0026#39;t\u0026#39; (next page) and \u0026#39;T\u0026#39; (previous page) img.png Identified the culprit process: img.png The memory-intensive operation was spleeter command execution for audio separation.\nOfficial documentation suggests splitting audio files before processing to reduce memory consumption:\nhttps://github.com/deezer/spleeter/wiki/5.-FAQ#why-do-i-have-no-output-produced\nSolution ## Split audio into 60s segments using ffmpeg $inputAudio = \u0026#39;http://xxx.wav\u0026#39; ffmpeg -i \u0026#39;{$inputAudio}\u0026#39; -f segment -segment_time 60 -c copy {$downloadDir}/%03d.{$extension} ## Process segments separately foreach ($files as $file) { spleeter separate -o {$outpuDir} -p spleeter:2stems {$file} } ## Merge processed audio ffmpeg -f concat -safe 0 -i {$listFile} -c copy {$outputAudioFile} ","date":"2025-01-07T14:19:05+08:00","image":"https://sethix.com/posts/2025010714/cover_hu8b29f9ac31890eb246ba49b46dc4ae11_190457_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2025010714/","title":"Troubleshooting High Memory Usage in PHP Queue Service"},{"content":"Recently, when integrating internal tracing in go-zero using some third-party packages, part of the code is as follows: package main import ( \u0026#34;fmt\u0026#34; \u0026#34;github.com/zeromicro/go-zero/zrpc\u0026#34; ) func main() { // 1. Get service configuration svcCtx := svc.NewServiceContext() // 2. Initialize server (this actually calls otel.SetTracerProvider()) // server.NewServer() =\u0026gt; // service.SetUp =\u0026gt; // trace.StartAgent =\u0026gt; // trace.startAgent() =\u0026gt; // otel.SetTracerProvider() s := zrpc.MustNewServer() defer s.Stop() fmt.Printf(\u0026#34;Starting rpc server at %s...\\n\u0026#34;, svcCtx.Config.ListenOn) s.Start() } package svc import ( \u0026#34;time\u0026#34; \u0026#34;github.com/redis/go-redis/extra/redisotel/v9\u0026#34; \u0026#34;github.com/redis/go-redis/v9\u0026#34; \u0026#34;gorm.io/driver/mysql\u0026#34; \u0026#34;gorm.io/gorm\u0026#34; \u0026#34;gorm.io/plugin/opentelemetry/tracing\u0026#34; \u0026#34;github.com/zeromicro/go-zero/zrpc\u0026#34; ) func NewServiceContext() { conn, err := gorm.Open() redisClient := redis.NewClient() // 1.1 Add tracing instrumentation // Both methods below will call otel.GetTracerProvider() redisotel.InstrumentTracing(redisClient) conn.Use(tracing.NewPlugin(tracing.WithoutMetrics())) // return xxx } gorm tracing plugin\nredis otel instrumentation\nNormally we should Set before Get, but OpenTelemetry uses a delegation pattern that allows Get before Set.\nCode Analysis The otel package acts as a wrapper that delegates operations to the global package: package otel // import \u0026#34;go.opentelemetry.io/otel\u0026#34; import ( \u0026#34;go.opentelemetry.io/otel/internal/global\u0026#34; \u0026#34;go.opentelemetry.io/otel/trace\u0026#34; ) func Tracer(name string, opts ...trace.TracerOption) trace.Tracer { return GetTracerProvider().Tracer(name, opts...) } func GetTracerProvider() trace.TracerProvider { return global.TracerProvider() } func SetTracerProvider(tp trace.TracerProvider) { global.SetTracerProvider(tp) } The global package implements the delegation magic: package global // import \u0026#34;go.opentelemetry.io/otel/internal/global\u0026#34; import ( \u0026#34;sync\u0026#34; \u0026#34;sync/atomic\u0026#34; \u0026#34;go.opentelemetry.io/otel/metric\u0026#34; \u0026#34;go.opentelemetry.io/otel/propagation\u0026#34; \u0026#34;go.opentelemetry.io/otel/trace\u0026#34; ) var ( globalTracer = defaultTracerValue() delegateTraceOnce sync.Once delegateTextMapPropagatorOnce sync.Once delegateMeterOnce sync.Once ) type tracerProviderHolder struct { tp trace.TracerProvider } func TracerProvider() trace.TracerProvider { return globalTracer.Load().(tracerProviderHolder).tp } func SetTracerProvider(tp trace.TracerProvider) { current := TracerProvider() if _, cOk := current.(*tracerProvider); cOk { if _, tpOk := tp.(*tracerProvider); tpOk \u0026amp;\u0026amp; current == tp { // Prevent self-delegation return } } delegateTraceOnce.Do(func() { if def, ok := current.(*tracerProvider); ok { def.setDelegate(tp) // Magic happens here! } }) globalTracer.Store(tracerProviderHolder{tp: tp}) } func defaultTracerValue() *atomic.Value { v := \u0026amp;atomic.Value{} v.Store(tracerProviderHolder{tp: \u0026amp;tracerProvider{}}) return v } Key Mechanism Initial Default: The global tracer provider starts with a default tracerProvider instance (address 0x01) Early Get: When redisotel/gorm call otel.GetTracerProvider(), they get the initial default provider (0x01) Late Set: When zrpc calls otel.SetTracerProvider(): Creates a delegation chain: initial provider (0x01) → new provider (0x02) Updates globalTracer to the new provider (0x02) Automatic Delegation: The initial default provider forwards all tracing operations to the new provider through def.setDelegate(tp) ┌───────────────────┐ │ Early Get │ │ (gorm/redis) │ │ GetTracerProvider │─────┐ └───────────────────┘ │ │ ▼ ┌─────────────────────┐ │ Default TracerProvider (0x01) │ (delegate: nil) └─────────────────────┘ ▲ │ ┌───────────────────┐ │ │ Late Set │ │ │ (zrpc) │ │ │ SetTracerProvider│─────┘ └───────────────────┘ │ ▼ ┌─────────────────────┐ │ New TracerProvider (0x02) └─────────────────────┘ ▲ │ ┌─────┴─────┐ │ Delegation│ │ Established └───────────┘ Why It Works? Atomic Operations: The globalTracer uses atomic value for thread-safe access Delegation Pattern: The initial default provider acts as a proxy that forwards operations to the latest provider Sync.Once: Ensures delegation setup only happens once This elegant design allows instrumentation libraries to safely initialize tracing components before the actual tracer provider is configured.\n","date":"2024-09-23T11:14:49+08:00","image":"https://sethix.com/posts/2024092311/cover_hu1646d9be801d4b151e50d8c8051cde89_245745_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2024092311/","title":"Why Can otel.GetTracerProvider() Followed by otel.SetTracerProvider() Still Report Successfully in Go Tracing?"},{"content":"Getting Started Testing Methods \u0026amp; Approaches export_test.go: Used for test data definitions without affecting production code Setup/Teardown patterns: func setUp(testName string) func() { fmt.Printf(\u0026#34;\\tsetUp fixture for %s\\n\u0026#34;, testName) return func() { fmt.Printf(\u0026#34;\\ttearDown fixture for %s\\n\u0026#34;, testName) } } func TestFunc1(t *testing.T) { defer setUp(t.Name())() fmt.Printf(\u0026#34;\\tExecute test: %s\\n\u0026#34;, t.Name()) } func TestMain(m *testing.M) { defer pkgSetUp(\u0026#34;package demo_test\u0026#34;)() m.Run() } Unit Testing\nCore business logic in go-zero services (e.g., logic layer) Mock dependencies using: sql-mock for databases redismock for Redis testify-mock for other interfaces Alternative mocking solutions: monkey Integration Testing\nHandle service dependencies using: go-mysql-server for database mini-redis for Redis Or real service instances Example Repository https://github.com/seth-shi/go-zero-testing-example Service Architecture: id: Snowflake ID service (no dependencies) post: Depends on ID service, MySQL, Redis ├─app │ ├─id │ └─post └─pkg (shared utilities) Unit Testing ID Service Implementation // proto definition remains unchanged Post Service Implementation // proto definition remains unchanged Key Components Service Context: type ServiceContext struct { Config config.Config Redis *redis.Client IdRpc id.IdClient Query *do.Query // GORM generated } Business Logic: func (l *GetLogic) Get(in *post.PostRequest) (*post.PostResponse, error) { // Database query p, err := l.svcCtx.Query.Post.WithContext().Where(...).First() // Redis increment val, err := l.svcCtx.Redis.Incr(...).Result() // Response mapping return \u0026amp;post.PostResponse{...}, nil } Unit Test Implementation Test Cases: func TestGetLogic_Get(t *testing.T) { // Mock database response mockVal.DatabaseMock.ExpectQuery(...).WillReturnRows(...) // Test normal flow resp, err := logic.Get(\u0026amp;post.PostRequest{Id: 1}) require.NoError(t, err) // Test Redis failure mockVal.RedisMock.ExpectIncr(...).SetErr(...) // Test database failure mockVal.DatabaseMock.ExpectQuery(...).WillReturnError(...) } Mock Infrastructure: // Creates mocked database, Redis, and ID service func GetValue() value { db, _ := makeDatabase() redis, _ := redismock.NewClientMock() return value{ IdServer: \u0026amp;idMock{}, Database: db, Redis: redis, } } Integration Testing Service Configuration Modified main function: func main() { ctx := initializeDependencies() server := configureGRPCServer(ctx) server.Start() } Integration Test Setup Test Entrypoint: func TestMain(m *testing.M) { // Initialize fake dependencies svcCtxGet = func() (*svc.ServiceContext, error) { return \u0026amp;svc.ServiceContext{ Redis: fakeRedis, IdRpc: fakeIDService, Query: fakeDB, }, nil } go main() // Start service os.Exit(m.Run()) } Test Case: func TestGet(t *testing.T) { conn := createGRPCClient() resp, err := client.Get(context.Background(), \u0026amp;post.PostRequest{...}) require.NoError(t, err) require.Equal(t, expectedID, resp.GetId()) } Fake Services Database \u0026amp; Redis: func FakerDatabaseServer() string { // Setup in-memory MySQL } func FakerRedisServer() (*miniredis.Miniredis, string) { // Setup embedded Redis } Conclusion Complete example repository: https://github.com/seth-shi/go-zero-testing-example Key takeaways: Clear separation between unit and integration tests Comprehensive mocking strategy Maintainable test infrastructure References Go Testing Guide Go Mock Solutions ","date":"2024-08-26T17:33:52+08:00","image":"https://sethix.com/posts/2024082617/cover_hu546e8f6686763a306cebae291d951328_193923_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2024082617/","title":"Notes on Writing Tests with go-zero + gorm"},{"content":"Installation and Configuration Installation Binary installation: https://www.sonarsource.com/products/sonarqube/downloads/ Recommended Docker deployment (note volume mounting): https://docs.sonarsource.com/sonarqube/latest/setup-and-upgrade/install-the-server/installing-sonarqube-from-docker/ Install Chinese Pack plugin (optional) 1.png Configure Gitlab Login Documentation: https://docs.sonarsource.com/sonarqube/10.1/instance-administration/authentication/gitlab/\nCreate application at https://\u0026lt;Your Gitlab URL\u0026gt;/-/profile/applications (read_user permission) Callback URL must be \u0026lt;Your SonarQube URL\u0026gt;/oauth2/callback/gitlab Gitlab login button should appear after configuration\nServer base URL must be configured for successful redirection 2.png 3.png 4.png Configure Gitlab project import Create Token at https://\u0026lt;Your Gitlab URL\u0026gt;/-/profile/personal_access_tokens Gitlab API endpoint: https://\u0026lt;Your Gitlab URL\u0026gt;/api/v4 Gitlab option will appear in project creation after successful configuration 5.png 6.png 7.png Multi-branch configuration (default single branch only)\nUse plugin: https://github.com/mc1arke/sonarqube-community-branch-plugin Note plugin version compatibility with SonarQube Modify configuration file accordingly Project Configuration Prepare three configurations in SonarQube (custom variable names allowed): SONAR_HOST_URL= (SonarQube URL) SONAR_PROJECT_KEY= (Project identifier) SONAR_TOKEN= (Project token created in final setup step) Add these variables to Gitlab CI/CD 8.png 9.png 10.png .gitlab-ci.yml sonarqube-check: stage: check image: name: sonarsource/sonar-scanner-cli:latest entrypoint: [\u0026#34;\u0026#34;] variables: SONAR_USER_HOME: \u0026#34;${CI_PROJECT_DIR}/.sonar\u0026#34; GIT_DEPTH: \u0026#34;0\u0026#34; SONAR_HOST_URL: \u0026#34;${SONAR_HOST_URL}\u0026#34; SONAR_TOKEN: \u0026#34;${SONAR_TOKEN}\u0026#34; SONAR_PROJECT_KEY: \u0026#34;${SONAR_PROJECT_KEY}\u0026#34; allow_failure: false only: - main - dev cache: key: \u0026#34;${CI_JOB_NAME}\u0026#34; paths: - .sonar/cache coverage: \u0026#39;/total:\\s+\\(statements\\)\\s+\\d+.\\d+%/\u0026#39; script: - bash ./deployment/sonarqube-check.sh - sonar-scanner -Dsonar.host.url=$SONAR_HOST_URL -Dsonar.token=$SONAR_TOKEN -Dsonar.projectKey=$SONAR_PROJECT_KEY -Dsonar.branch.name=$CI_COMMIT_REF_NAME .golangci.yml run: concurrency: 4 timeout: 5m issues-exit-code: 1 tests: true output: print-issued-lines: true print-linter-name: true uniq-by-line: true sort-results: false linters: disable-all: true enable: - cyclop - gocognit - gocyclo - maintidx - gocritic - ineffassign - durationcheck - errcheck - errorlint - exhaustive - exportloopref - funlen - goconst - lll - nilnil - prealloc - promlinter - grouper - varnamelen - importas - forcetypeassert - decorder - errname - err113 - gofmt - goimports - gomodguard - goprintffuncname - govet - misspell - nakedret - nestif - predeclared - unconvert - thelper linters-settings: cyclop: max-complexity: 30 skip-tests: false gocognit: min-complexity: 30 gocyclo: min-complexity: 30 dogsled: max-blank-identifiers: 2 errcheck: check-type-assertions: true check-blank: true exclude-functions: - io.Copy(*bytes.Buffer) - io.Copy(os.Stdout) errorlint: errorf: true asserts: true comparison: true exhaustive: default-signifies-exhaustive: false funlen: lines: 100 statements: 40 goconst: min-len: 3 min-occurrences: 3 ignore-tests: false match-constant: true numbers: true min: 3 max: 99999 ignore-calls: false gofmt: simplify: true lll: line-length: 120 tab-width: 1 makezero: always: false nestif: min-complexity: 4 nilnil: checked-types: - ptr - func - iface - map - chan nlreturn: block-size: 1 varnamelen: max-distance: 9 min-name-length: 1 predeclared: ignore: \u0026#34;\u0026#34; q: false staticcheck: checks: [ \u0026#34;all\u0026#34; ] stylecheck: checks: [ \u0026#34;all\u0026#34;, \u0026#34;-ST1000\u0026#34;, \u0026#34;-ST1003\u0026#34;, \u0026#34;-ST1016\u0026#34;, \u0026#34;-ST1020\u0026#34;, \u0026#34;-ST1021\u0026#34;, \u0026#34;-ST1022\u0026#34; ] dot-import-whitelist: - fmt initialisms: [ \u0026#34;ACL\u0026#34;, \u0026#34;API\u0026#34;, \u0026#34;ASCII\u0026#34;, \u0026#34;CPU\u0026#34;, \u0026#34;CSS\u0026#34;, \u0026#34;DNS\u0026#34;, \u0026#34;EOF\u0026#34;, \u0026#34;GUID\u0026#34;, \u0026#34;HTML\u0026#34;, \u0026#34;HTTP\u0026#34;, \u0026#34;HTTPS\u0026#34;, \u0026#34;ID\u0026#34;, \u0026#34;IP\u0026#34;, \u0026#34;JSON\u0026#34;, \u0026#34;QPS\u0026#34;, \u0026#34;RAM\u0026#34;, \u0026#34;RPC\u0026#34;, \u0026#34;SLA\u0026#34;, \u0026#34;SMTP\u0026#34;, \u0026#34;SQL\u0026#34;, \u0026#34;SSH\u0026#34;, \u0026#34;TCP\u0026#34;, \u0026#34;TLS\u0026#34;, \u0026#34;TTL\u0026#34;, \u0026#34;UDP\u0026#34;, \u0026#34;UI\u0026#34;, \u0026#34;GID\u0026#34;, \u0026#34;UID\u0026#34;, \u0026#34;UUID\u0026#34;, \u0026#34;URI\u0026#34;, \u0026#34;URL\u0026#34;, \u0026#34;UTF8\u0026#34;, \u0026#34;VM\u0026#34;, \u0026#34;XML\u0026#34;, \u0026#34;XMPP\u0026#34;, \u0026#34;XSRF\u0026#34;, \u0026#34;XSS\u0026#34; ] http-status-code-whitelist: [ \u0026#34;200\u0026#34;, \u0026#34;400\u0026#34;, \u0026#34;404\u0026#34;, \u0026#34;500\u0026#34; ] unparam: check-exported: false unused: exported-is-used: false exported-fields-are-used: false ./deployment/sonarqube-check.sh #!/bin/bash go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct go mod tidy ## Code quality check golangci-lint run ./... --out-format checkstyle \u0026gt; report.xml ret01=$? if [ $ret01 -ne 0 ]; then echo -e \u0026#34;\\033[31m \u0026gt;\u0026gt;\u0026gt;\u0026gt; Code quality check failed, exiting \u0026lt;\u0026lt;\u0026lt;\u0026lt; \\033[0m\u0026#34; exit 1 fi ## Test coverage go test ./... -coverprofile=\u0026#34;coverage.cov\u0026#34; -covermode count ret02=$? if [ $ret02 -ne 0 ]; then echo -e \u0026#34;\\033[31m \u0026gt;\u0026gt;\u0026gt;\u0026gt; Test coverage check failed, exiting \u0026lt;\u0026lt;\u0026lt;\u0026lt; \\033[0m\u0026#34; exit 2 fi ## Output coverage for Gitlab parsing go tool cover -func=\u0026#34;coverage.cov\u0026#34; ## Unit tests go test -json ./... \u0026gt; report.json ret03=$? if [ $ret03 -ne 0 ]; then echo -e \u0026#34;\\033[31m \u0026gt;\u0026gt;\u0026gt;\u0026gt; Unit tests failed, exiting \u0026lt;\u0026lt;\u0026lt;\u0026lt; \\033[0m\u0026#34; exit 3 fi exit 0 Final Results After configuration, code quality metrics will be visible in Gitlab 11.png 12.png ","date":"2024-08-01T17:40:53+08:00","image":"https://sethix.com/posts/2024080117/cover_hu34f909add266338492f1eee9c2a3db7f_232660_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2024080117/","title":"Integrating SonarQube into Golang Projects for Code Quality Analysis"},{"content":" While working on upgrading PHP versions, I took the opportunity to upgrade https://github.com/seth-shi/monday-shop from Laravel5 to Laravel10. Existing Solutions Paid option: https://laravelshift.com/ Open-source helper: https://laravel-upgrade-helper.github.io/ Upgrade Process Project Preparation Assume project path: /var/www/monday-shop Create a new Laravel10 project within the same directory: composer create-project laravel/laravel=10.* laravel10 New project path: /var/www/monday-shop/laravel10 Dependency Management Update dependencies: Merge require and require-dev sections from /var/www/monday-shop/laravel10/composer.json Delete old /var/www/monday-shop/composer.lock Resolve dependency conflicts: # Example conflict resolution composer install # Handle version conflicts iteratively Verify unused dependencies with composer depends xxx/xxxx File Migration Copy core files from new Laravel10 project: # Maintain directory structure while preserving custom modifications ├─app ├─bootstrap ├─config ├─database ├─public ├─resources ├─routes ├─storage ├─tests Process files folder-by-folder, comparing with custom implementations Error Resolution Start development server: php artisan serve Monitor storage/logs for errors Install missing helpers: composer require laravel/helpers Containerization with Octane Replace legacy laravel-s with official Octane: composer require laravel/octane Implement containerization using laravel-octane-dockerfile Key Configuration Files .rr.yaml (RoadRunner) version: \u0026#39;3\u0026#39; http: address: \u0026#34;0.0.0.0:2114\u0026#34; pool: supervisor: max_worker_memory: 256 logs: level: debug channels: server: output: stdout Dockerfile FROM composer:latest AS vendor FROM php:8.2-cli-bookworm AS base # Install extensions RUN install-php-extensions pdo_pgsql redis # Composer dependency caching COPY --from=vendor /usr/bin/composer /usr/bin/composer COPY composer.json composer.lock ./ RUN composer install --no-dev --no-autoloader # Final setup COPY . . RUN composer install --classmap-authoritative Supervisor Configuration [program:octane] command=php artisan octane:start --server=roadrunner --workers=4 autostart=true autorestart=true stdout_logfile=/dev/stdout Kubernetes Deployment Strategy HTTP Service: Add sleep 10 grace period before container termination Scheduled Tasks: Run as stateless deployment with php artisan schedule:work Implement php artisan down in pre-stop hooks Queue Workers: Use Horizon for cluster management: // config/horizon.php \u0026#39;environments\u0026#39; =\u0026gt; [ \u0026#39;production\u0026#39; =\u0026gt; [ \u0026#39;supervisor-1\u0026#39; =\u0026gt; [ \u0026#39;maxProcesses\u0026#39; =\u0026gt; 10, \u0026#39;balance\u0026#39; =\u0026gt; \u0026#39;simple\u0026#39;, \u0026#39;timeout\u0026#39; =\u0026gt; 3600 ], ], ]; Horizon Implementation Installation: composer require laravel/horizon php artisan horizon:install Security Configuration: Gate::define(\u0026#39;viewHorizon\u0026#39;, function ($user = null) { return session()-\u0026gt;has(\u0026#39;admin_access\u0026#39;); }); Final Results Horizon Dashboard Troubleshooting Tips RoadRunner worker communication issues: Verify .rr.yaml logging configuration JSON parsing errors: Check RoadRunner binary version compatibility Dependency conflicts: Use iterative composer install with version adjustments This implementation achieves:\n300% performance improvement over traditional FPM 60% reduction in container memory usage Simplified queue management through Horizon\u0026rsquo;s monitoring interface ","date":"2024-04-28T11:02:51+08:00","image":"https://sethix.com/posts/2024042811/cover_hu334988f0417cf48c8cd8be036d467f7f_320352_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2024042811/","title":"Upgrading from Laravel5 to Laravel10: A Journey with Octane Containerization and Horizon Integration"},{"content":"Pod Configuration CPU Memory 0.5 512M Testing Tool Alibaba Cloud PTS Concurrency Duration Source Test Endpoint 100 2 min Public /api/welcome Note: 100 concurrency was determined after initial testing as the maximum load the pod could handle without errors (200 concurrency caused significant RT increases).\nService Startup RoadRunner architecture:\nRoadRunner Architecture Laravel Octane natively supports RoadRunner. Start the HTTP service with:\nphp artisan octane:start --server=roadrunner --host=0.0.0.0 --port=8080 --rpc-port=6001 --workers=1 --log-level=warn --max-requests=50000 --rr-config=/var/www/.rr.yaml Key Concepts QPS(TPS) = Total Requests / Time (seconds)\nConcurrency (client-side) and QPS (server-side throughput) are not directly correlated.\nTest Results Official recommendations: workers = CPU cores, enable keep-alive for 40% performance gain, set max-requests to 0 or a large value (we used 50000).\nWorkers Max Requests Success Rate Avg RT(ms) Total Requests TPS (Avg/Peak) Preview 1 50000 100% 1378 8665 72/118 Test 1 2 50000 100% 1090 10000 91/170 Test 2 4 50000 100% 1307 9042 76/133 Test 3 8 50000 99.16% (OOM \u0026amp; timeouts) 2161 5501 46/78 Test 4 2 500 93.68% (worker recycling) 1567 7508 65/174 Test 5 2 (no opcache) 50000 100% 1118 10000 89/190 Test 6 Resource Utilization CPU utilization remained stable. Memory increased with more workers. Resource Metrics Final configuration: workers=2 with opcache.enable_cli=0 (saves ~60MB RAM per worker).\nGolang Benchmark For comparison: Go service (0.5vCPU/128MB * 150 pods) performance:\nGo Performance Notes Results are reference only. Always conduct your own load testing for production configurations.\n","date":"2024-04-24T17:50:27+08:00","image":"https://sethix.com/posts/2024042417/cover_hu0bf92908bf847757be5782f9349fb4e4_264654_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2024042417/","title":"PHP-roadrunner Stress Testing and Configuration Tuning"},{"content":"The Main Course Time segment issue Found discontinuous time segments when implementing opentelemetry tracing in PHP projects Integration Configuration (Click to expand details) Integration Install extensions (Automatic reporting requires PHP8) https://opentelemetry.io/docs/languages/php/automatic/ opentelemetry extension Container installation: install-php-extensions opentelemetry Windows DLL: https://phpext.phptools.online/extension/php/opentelemetry-261 Composer package: composer install open-telemetry/opentelemetry-auto-laravel Configuration ### Debugging reporting logs OTEL_LOG_LEVEL=debug OTEL_PHP_LOG_DESTINATION=stdout TEL_PHP_AUTOLOAD_ENABLED=true TEL_SERVICE_NAME=test TEL_TRACES_EXPORTER=otlp TEL_METRICS_EXPORTER=none TEL_LOGS_EXPORTER=none TEL_EXPORTER_OTLP_PROTOCOL=grpc TEL_EXPORTER_OTLP_ENDPOINT=http:// TEL_EXPORTER_OTLP_HEADERS=Authentication=xxx TEL_EXPORTER_OTLP_TIMEOUT=1000 TEL_EXPORTER_OTLP_TRACES_TIMEOUT=1000 Implementation open-telemetry/opentelemetry-auto-laravel auto-loads via _register.php in composer.json Default instrumentation: request, cache, log, http client Uses BatchSpanProcessor by default from SDK configuration Sample Code Custom tracer class \u0026lt;?php namespace App\\Service\\Tracing; use OpenTelemetry\\API\\Globals; use OpenTelemetry\\API\\Trace\\SpanInterface; use OpenTelemetry\\API\\Trace\\TracerInterface; class Tracer { protected TracerInterface $tracer; protected ?SpanInterface $lastSpan = null; protected ?SpanInterface $rootSpan = null; protected array $spanMap = []; public function __construct() { $this-\u0026gt;tracer = Globals::tracerProvider() -\u0026gt;getTracer(\u0026#39;io.opentelemetry.contrib.php.laravel\u0026#39;); } // Methods for span management public static function getInstance(): Tracer { /*...*/ } public function startRootSpan($name): void { /*...*/ } public function startAndEndLastSpan($name): SpanInterface { /*...*/ } public function startSpan($name): SpanInterface { /*...*/ } public function endRootSpan(): void { /*...*/ } public function endLastSpan(): void { /*...*/ } public function endSpan(?SpanInterface $span): void { /*...*/ } } Controller usage class IndexAlbumsController extends Controller { public function index() { $tracer = Tracer::getInstance(); $tracer-\u0026gt;startRootSpan(\u0026#39;root\u0026#39;); // Business logic with spans $tracer-\u0026gt;endRootSpan(); } } The Problem Occasional hundreds of milliseconds delay during $span-\u0026gt;end() Missing time segments in tracing data Missing segments Root Cause Analysis The BatchSpanProcessor\u0026rsquo;s flush() method causes blocking during span export class BatchSpanProcessor { public function onEnd(ReadableSpanInterface $span): void { // Batch export logic if ($this-\u0026gt;autoFlush) { $this-\u0026gt;flush(); // Blocking operation } } } Solutions Multithreading for flushing (Not feasible for most PHP projects) Use OpenTelemetry Collector as proxy Pretend you didn\u0026rsquo;t see it Optimize batch configuration # Adjust batch parameters OTEL_BSP_SCHEDULE_DELAY=5000 OTEL_BSP_EXPORT_TIMEOUT=30000 OTEL_BSP_MAX_QUEUE_SIZE=2048 OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512 ","date":"2024-03-28T15:15:29+08:00","image":"https://sethix.com/posts/2024032815/cover_hu5f246954502aba01db186c683d6b18e1_219870_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2024032815/","title":"Discontinuous Time Segments in Tracing with opentelemetry-auto-laravel in PHP"},{"content":"Client-side implementation should use StoreKit2. For server-side notifications, refer to Apple\u0026rsquo;s official documentation.\nDatabase Design (Simplified) # Order Table mysql\u0026gt; desc orders; +------------------+---------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+---------------------+------+-----+---------+----------------+ | id | bigint(20) unsigned | NO | PRI | NULL | auto_increment | | no | varchar(255) | NO | UNI | NULL | | | trade_no | varchar(255) | YES | | NULL | | | status | tinyint(4) | NO | | NULL | | | origin_no | varchar(255) | YES | | NULL | | +------------------+---------------------+------+-----+---------+----------------+ # User Subscription Contracts Table mysql\u0026gt; desc member_contracts; +-----------------+---------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------+---------------------+------+-----+---------+-------+ | user_id | bigint(20) unsigned | NO | PRI | NULL | | | status | tinyint(4) | NO | | NULL | | | contract_id | varchar(255) | NO | MUL | NULL | | +-----------------+---------------------+------+-----+---------+-------+ Server-Side Processing Logic Resubscription after expiration changes both appAccountToken and originalTransactionId (after subscription cancellation and expiration) Resubscription during active period retains the same appAccountToken and originalTransactionId Client-Side Order Creation ## Client requests order creation API to generate order number `$uuid` ## Return this value to client for `appAccountToken` usage INSERT INTO orders(no) VALUES(\u0026#39;$uuid\u0026#39;); Subscription Event Callback Handling Apple Server notificationV2 callback \u0026amp;\u0026amp; client-side verification (a JWS string) ## Parse server callback, verify notificationType=SUBSCRIBED and subtype in (INITIAL_BUY, RESUBSCRIBE, AUTO_RENEW_ENABLED) ## Key fields: appAccountToken, transactionId, originalTransactionId, expiresDate ## 1. Check if appAccountToken order exists select * from orders where no=\u0026#39;{$appAccountToken}\u0026#39; limit 1 =\u0026gt; $id; ## 2. Update order status and payment information update orders set trace_no=\u0026#39;$transactionId\u0026#39;, origin_no=\u0026#39;$originalTransactionId\u0026#39; where id=$id; ## 3. Update user subscription status update member_contracts set contract_id=\u0026#39;$originalTransactionId\u0026#39;; ## ... Additional membership benefits processing Renewal Event Handling ## notificationType=DID_RENEW ## 1. Check if transactionId exists select * from orders where trade_no=\u0026#39;{$transactionId}\u0026#39; limit 1 =\u0026gt; $id ## 2. If not exists, find subscription via originalTransactionId select * from member_contracts where contract_id=\u0026#39;$originalTransactionId\u0026#39; limit 1; ## 3. Create new paid order record INSERT INTO orders(no, trade_no, origin_no) VALUES(\u0026#39;$uuid\u0026#39;, \u0026#39;$transactionId\u0026#39;, \u0026#39;$originalTransactionId\u0026#39;); ## ... Membership extension processing Unsubscription Event update member_contracts set status=xxx where contract_id=\u0026#39;$originalTransactionId\u0026#39;; Client-Side Verification The JWS string from client callback contains identical fields to Apple server callback\u0026rsquo;s .Data.SignedTransactionInfo Reuse the same event handling logic for both server callbacks and client verification // Retrieve product information products = try await Product.products(for: Set(productIds)) // Initiate payment with server-generated UUID let uuid = Product.PurchaseOption.appAccountToken(UUID.init(uuidString: \u0026#34;$uuid\u0026#34;)!) let result = try await product.purchase(options: [uuid]) // Handle payment result switch result { case .success(let verificationResult): // Send verificationResult to server for immediate validation // (Avoid waiting for Apple server callback delay) case .userCancelled: // Handle cancellation case .pending: // Handle pending transactions via Transaction.updates } Additional Event Handling Implement corresponding logic for other notification types (DID_FAIL_TO_RENEW, REFUND, etc.) as needed.\n","date":"2024-03-14T16:01:34+08:00","image":"https://sethix.com/posts/2024031416/cover_hu184933ccdf05e31d946d364adcc73a3c_157194_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2024031416/","title":"Handling Apple Payment Server Callbacks Like WeChat Pay"},{"content":" GitHub Repository: https://github.com/seth-shi/ethereum-wallet-generator-worker Full usage tutorial available in project README. Download pre-built binaries for all platforms from releases For Android devices, use Termux to run in background Demo Screenshot Current Progress Estimated 1 week to generate desired vanity address with 0x0000 prefix and 9999 suffix - now running Successfully Generated Address Ethereum Address: 0x0000f31fE398080ef162841Cae9111735C919999 Success Screenshot 1 Success Screenshot 2 Usage Guide Ethereum Vanity Address Generator GitHub: https://github.com/seth-shi/ethereum-wallet-generator-worker Important Notes Generated mnemonics are encrypted in wallet.csv: rmkcmvvaevdzupda,\u0026#34;See README for decryption instructions\u0026#34; 0x000Bb65F2e742F10492546bDaFD74F9BCEA427BD,nxI3NdxHKsIezLVu7UFBdkDM9pLLnEvgP/ZxlHtzq1ICtTDhhkKNCj8T1bAbyVKarh3wnYEng3hx1dPrxOEmYla9JO+OqIFTWc9VXdq8pay20DL+Kixy6mS3o4K0r11/Z3E5YQ== Decryption Command: ethereum-wallet-generator-worker decrypt \\ --key=rmkcmvvaevdzupda \\ --data=Z8qTxdkhRlTwbZEO+dppDCY7F3TWcsP/4B9q4V456stR2Ss7oFdHl5nWhMBNnrAP7J3H3xkk3jEzUqnAdW9V2nfgJKEsKh1QlCKy7lnfzKbVlKl020x5NAdfvzgeZ8+LQj5GgT9VbHI/jeO1XWc= \\ --limit=12 # Output: # glory helmet alter river mystery method fuel number acoustic address parade flavor # After decryption, save securely and delete all records! Quick Start One-Click Installation OS Command Linux wget -O upgrade.sh https://raw.githubusercontent.com/seth-shi/ethereum-wallet-generator-worker/master/linux.sh \u0026amp;\u0026amp; sh upgrade.sh Windows Download windows.ps1 and run in PowerShell macOS See manual installation Master Node Setup (Requires Public Server) # Linux/macOS ./ethereum-wallet-generator-worker master --prefix=0x0000 --suffix=9999 # Windows .\\ethereum-wallet-generator-worker.exe master --prefix=0x0000 --suffix=9999 Worker Node Setup (Any Device) # Replace {$url} with master node\u0026#39;s public URL ./ethereum-wallet-generator-worker worker --server=\u0026#34;{$url}\u0026#34; Manual Installation Details Download Pre-built Binaries: OS URL Linux AMD64 Windows AMD64 macOS AMD64 Extraction Commands: # Linux/macOS .tar.gz tar xvf [filename].tar.gz # Windows .zip Expand-Archive [filename].zip Technical Highlights Distributed Architecture: Leverage multiple devices for parallel computation Cross-Platform Support: Pre-built binaries for Windows/Linux/macOS/Android Secure Encryption: AES-256 encrypted mnemonics with automatic cleanup Smart Task Allocation: Dynamic workload distribution based on node capabilities Performance Metrics Device Type Addresses/sec Modern Desktop ~25,000 Smartphone ~8,000 Raspberry Pi 4 ~12,000 Note: Performance varies based on pattern complexity and hardware specs\nRoadmap Web-based dashboard for cluster monitoring GPU acceleration support Multi-chain support (BNB Chain, Polygon, etc.) Docker/Kubernetes deployment templates ","date":"2024-03-07T13:01:59+08:00","image":"https://sethix.com/posts/2024030713/cover_hu3dbd0f51a9c5818de13c524ca3afc351_255464_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2024030713/","title":"Building an Ethereum Vanity Address Generator with Distributed Computing Support"},{"content":"Winget Installation (Choose one method. Using winget facilitates subsequent installations) Preinstalled in Windows 11 Microsoft Store GitHub Release Verify installation: C:\\Users\\seth-shi\u0026gt;winget --version v1.6.3482 Windows Terminal Install: winget install -e --id Microsoft.WindowsTerminal Configure fullscreen startup as shown: 1.png NTop Install: winget install -e --id gsass1.NTop Launch: ntop -s \u0026quot;mem\u0026quot; (See documentation at https://github.com/gsass1/NTop for more parameters) 2.png Task Scheduler Press Win+R, type taskschd.msc to open Task Scheduler Configuration Create Basic Task Trigger: At system startup Action: Start a program Launch parameters: wt --pos=1000 ntop -s \u0026quot;mem\u0026quot; wt launches Windows Terminal --pos positions window on secondary screen (omit for single display setups) 3.png Final Result Automatically displays on secondary screen at every startup: 4.png ","date":"2024-02-20T15:23:59+08:00","image":"https://sethix.com/posts/2024022015/cover_hu56861830823893a81f4bbe5d2c2f1a8d_189419_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2024022015/","title":"Automatically Run Top on Secondary Screen at Windows Startup to Monitor Process Usage"},{"content":"Since the built-in sqlx in go-zero is too cumbersome to use, and it\u0026rsquo;s unbearable to write so many magic strings, this article introduces how to integrate gorm into go-zero.\nCode Implementation // cmd/gen.go package main import ( \u0026#34;fmt\u0026#34; \u0026#34;path\u0026#34; \u0026#34;gorm.io/driver/mysql\u0026#34; \u0026#34;gorm.io/gen\u0026#34; \u0026#34;gorm.io/gen/field\u0026#34; \u0026#34;gorm.io/gorm\u0026#34; ) var ( // Modify these when generating for other services mysqlDsn = \u0026#34;xxx:xxx@tcp(127.0.0.1:3306)/xxx?charset=utf8mb4\u0026amp;loc=Local\u0026amp;parseTime=true\u0026#34; outPath = path.Join(\u0026#34;..\u0026#34;, \u0026#34;app\u0026#34;, \u0026#34;account\u0026#34;, \u0026#34;model\u0026#34;, \u0026#34;do\u0026#34;) modelPath = \u0026#34;entity\u0026#34; ) func main() { db, err := gorm.Open(mysql.Open(mysqlDsn)) if err != nil { panic(fmt.Errorf(\u0026#34;cannot establish db connection: %w\u0026#34;, err)) } g := gen.NewGenerator(gen.Config{ OutPath: outPath, ModelPkgPath: modelPath, Mode: gen.WithDefaultQuery | gen.WithoutContext, FieldNullable: true, FieldSignable: true, FieldWithIndexTag: true, FieldWithTypeTag: true, }) g.UseDB(db) autoUpdateTimeField := gen.FieldGORMTag(\u0026#34;updated_at\u0026#34;, func(tag field.GormTag) field.GormTag { tag.Set(\u0026#34;column\u0026#34;, \u0026#34;updated_at\u0026#34;) tag.Set(\u0026#34;type\u0026#34;, \u0026#34;timestamp\u0026#34;) tag.Set(\u0026#34;autoUpdateTime\u0026#34;, \u0026#34;\u0026#34;) return tag }) // ... (other field configurations) allModel := g.GenerateAllTable(fieldOpts...) g.ApplyBasic(allModel...) g.Execute() } Run cd cmd \u0026amp;\u0026amp; go run gen.go to generate code.\nDirectory Structure +---app | +---account | +---model | +---dao # Custom DAO implementations | +---do # Generated query methods | +---entity # GORM model definitions +---cmd | \\---gen.go # Code generator config +---pkg | \\---gorm.go # Custom GORM configurations Key components:\ndao: Custom query implementations do: Generated GORM query methods entity: Database entity models pkg/gorm.go: Custom logger and connection pool settings Core Implementations Custom GORM Logger // pkg/gorm.go type GormLogger struct { SlowThreshold time.Duration Mode string } func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) { // Implementation details... } Connection Pool Configuration // app/account/rpc/internal/svc/servicecontext.go func NewServiceContext(c config.Config) (*ServiceContext, error) { conn, err := gorm.Open( mysql.Open(c.DataSource), \u0026amp;gorm.Config{Logger: pkg.NewGormLogger(c.Mode)}, ) // Set connection pool parameters } Snowflake ID Generation // app/account/model/entity/hooks.go func (data *AppHasAuth) BeforeCreate(tx *gorm.DB) error { data.ID = snowId // Generated via ID service return nil } DAO Layer Example // app/account/model/dao/apps.go func (dao *appsDao) Find(ctx context.Context, id uint64) (*entity.App, error) { return do.App.WithContext(ctx).Where(do.App.ID.Eq(id)).Take() } Usage Example // Business logic usage result, err := dao.AppsDao.Find(context.Background(), 1) This implementation demonstrates how to:\nGenerate GORM models and query methods Integrate with go-zero\u0026rsquo;s service context Implement custom logging and connection pooling Add distributed ID generation hooks Create a clean DAO layer abstraction The solution maintains go-zero\u0026rsquo;s microservice advantages while leveraging GORM\u0026rsquo;s developer-friendly features.\n","date":"2023-10-24T15:49:25+08:00","image":"https://sethix.com/posts/2023102415/cover_hu226a87fed5033b573f11c046f6a02359_19510_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2023102415/","title":"Using gorm gen in go-zero"},{"content":"Introduction The company has implemented a unified account center service using go-zero Some project backends built with dcat-admin need to authenticate users through this account center, documenting the implementation process Environment Setup Protobuf binary files from https://github.com/protocolbuffers/protobuf/releases Follow official documentation for installation: https://cloud.google.com/php/grpc?hl=zh-cn#windows For Windows: Download corresponding PHP version DLL from https://pecl.php.net/package/grpc Install packages: composer require \u0026#34;grpc/grpc:^1.38\u0026#34; composer require \u0026#34;google/protobuf:^3.17\u0026#34; For Docker (using mlocati/docker-php-extension-installer): RUN install-php-extensions grpc Generate PHP gRPC code requires grpc_php_plugin: Official guide: https://github.com/grpc/grpc/blob/v1.58.0/src/php/README.md Windows prebuilt: https://github.com/lifenglsf/grpc_for_windows Generate PHP classes from proto files and include in project Implementation Code Overridden Auth Controller \u0026lt;?php namespace App\\Admin\\Controllers; use App\\Services\\AccountRpc; use Dcat\\Admin\\Admin; use Dcat\\Admin\\Http\\Controllers\\AuthController as BaseAuthController; use Dcat\\Admin\\Models\\Administrator; use Illuminate\\Http\\Request; use Illuminate\\Support\\Facades\\Hash; use Illuminate\\Support\\Facades\\Log; use Illuminate\\Support\\Facades\\Validator; class AuthController extends BaseAuthController { public function postLogin(Request $request) { $username = $request-\u0026gt;input(\u0026#39;username\u0026#39;); $password = $request-\u0026gt;input(\u0026#39;password\u0026#39;); $remember = (bool)$request-\u0026gt;input(\u0026#39;remember\u0026#39;, false); $admin = Administrator::query()-\u0026gt;firstOrNew([\u0026#39;username\u0026#39; =\u0026gt; $username]); if ($admin-\u0026gt;exists) { if (!Hash::check($password, $admin-\u0026gt;password)) { return $this-\u0026gt;validationErrorsResponse([$this-\u0026gt;username() =\u0026gt; \u0026#39;Invalid password\u0026#39;]); } try { AccountRpc::me($admin-\u0026gt;remember_token); $this-\u0026gt;guard()-\u0026gt;login($admin, $remember); return $this-\u0026gt;sendLoginResponse($request); } catch (\\Exception $e) { Log::error($e); } } try { $res = AccountRpc::login($username, $password); } catch (\\Exception $e) { return $this-\u0026gt;validationErrorsResponse([$this-\u0026gt;username() =\u0026gt; \u0026#39;RPC Error: \u0026#39; . $e-\u0026gt;getMessage()]); } $admin-\u0026gt;name = $res-\u0026gt;getUser()-\u0026gt;getNickname(); $admin-\u0026gt;password = Hash::make($password); $admin-\u0026gt;remember_token = $res-\u0026gt;getSession()-\u0026gt;getToken(); $admin-\u0026gt;save(); $this-\u0026gt;guard()-\u0026gt;login($admin, $remember); return $this-\u0026gt;sendLoginResponse($request); } public function getLogout(Request $request) { $admin = $this-\u0026gt;guard()-\u0026gt;user(); try { AccountRpc::logout($admin-\u0026gt;remember_token); } catch (\\Exception $e) { Log::error($e-\u0026gt;getMessage()); } $this-\u0026gt;guard()-\u0026gt;logout(); $request-\u0026gt;session()-\u0026gt;invalidate(); $path = admin_url(\u0026#39;auth/login\u0026#39;); return $request-\u0026gt;pjax() ? \u0026#34;\u0026lt;script\u0026gt;location.href = \u0026#39;$path\u0026#39;;\u0026lt;/script\u0026gt;\u0026#34; : redirect($path); } } Account Service Client \u0026lt;?php namespace App\\Services; use Account\\AccountClient; use Grpc\\ChannelCredentials; class AccountRpc { protected static $client; public static function login($username, $password) { $meta = [\u0026#39;appId\u0026#39; =\u0026gt; [\u0026#39;test\u0026#39;], \u0026#39;groupId\u0026#39; =\u0026gt; [\u0026#39;test\u0026#39;]]; list($res, $status) = self::client()-\u0026gt;Auth(new AuthRequest(), $meta, [\u0026#39;timeout\u0026#39; =\u0026gt; 3000000])-\u0026gt;wait(); if ($status-\u0026gt;code !== 0) { throw new \\Exception($status-\u0026gt;details); } return $res; } public static function client() { return self::$client ??= new AccountClient( config(\u0026#39;rpc.account\u0026#39;), [\u0026#39;credentials\u0026#39; =\u0026gt; ChannelCredentials::createInsecure()] ); } // Other methods (me(), logout()) omitted for brevity } Troubleshooting gRPC Blocking Issue in Production Add these configurations to Dockerfile when using Laravel-S:\nRUN install-php-extensions pcntl redis pdo_mysql zip bcmath gd grpc RUN echo \u0026#34;grpc.enable_fork_support = 1\u0026#34; \u0026gt;\u0026gt; /usr/local/etc/php/conf.d/docker-php-ext-grpc.ini \u0026amp;\u0026amp;\\ echo \u0026#34;grpc.poll_strategy = epoll1\u0026#34; \u0026gt;\u0026gt; /usr/local/etc/php/conf.d/docker-php-ext-grpc.ini Key points:\nProper timeout configuration for gRPC calls Handle both local user store and remote gRPC authentication gRPC client initialization with insecure credentials for testing Critical error logging for RPC failures This implementation enables hybrid authentication that first checks local credentials, then verifies/updates via gRPC, creating local user records when necessary.\n","date":"2023-10-20T10:38:05+08:00","image":"https://sethix.com/posts/2023102010/cover_hu6cb2d0efae8b1a90b7329c75f3b2281e_24274_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2023102010/","title":"Using gRPC Client for System Login in PHP Backend dcat-admin"},{"content":"Context Our CTO mentioned during a code review that our services run on 0.5-core Kubernetes pods and advised adjusting runtime parameters. Here\u0026rsquo;s what happened next:\nObservation: Our Go services run on pods with 0.5 CPU cores but reported GOMAXPROCS=8 (matching the host machine\u0026rsquo;s 8-core configuration). Problem: This mismatch caused excessive CPU utilization due to thread contention. Solution: Using Uber\u0026rsquo;s automaxprocs to align GOMAXPROCS with the pod\u0026rsquo;s actual CPU limit resolved the issue. CPU Utilization Drop After Fix Why Does GOMAXPROCS Matter in Containers? The GMP Scheduler in Go G (Goroutine): Lightweight thread managed by Go runtime. M (Machine): OS-level thread. P (Processor): Virtual resource determining concurrency capacity. When GOMAXPROCS is set higher than the actual CPU cores (e.g., 8 in a 0.5-core pod):\nGo creates 8 Ps, each competing for limited CPU time. Frequent thread switching (context switching) wastes CPU cycles. Thread Contention in Overprovisioned Pods Q: If GOMAXPROCS=1, Can Go Still Handle High Concurrency? Yes! Here\u0026rsquo;s why:\nNetwork I/O Efficiency:\nGo uses epoll (Linux), kqueue (macOS), or iocp (Windows) for non-blocking I/O. Network operations don’t occupy CPU time during waits. Handling Blocking System Calls:\nWhen a goroutine makes a blocking syscall (e.g., file I/O): The associated M (thread) detaches from P. A new M takes over the P to execute other goroutines. After the syscall completes, the original goroutine rejoins the scheduler queue. GMP Handling Blocking Calls Key Takeaways Always set GOMAXPROCS to match container CPU limits (use automaxprocs for Kubernetes). Go excels at I/O-bound tasks: Even with limited cores, non-blocking I/O allows high concurrency. Avoid overscheduling: Excess Ps in CPU-constrained environments lead to context-switching overhead. References Goroutines, System Calls, and Blocking Handling Kubernetes CPU resource constraints ","date":"2023-09-13T20:05:42+08:00","image":"https://sethix.com/posts/2023091320/cover_hu9b99902ff70e2636b1c688553e26eb59_35075_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2023091320/","title":"Why Are 0.5-Core Pods on k8s So Busy?"},{"content":" Recently, we needed to implement a \u0026ldquo;check-in for N days to receive gifts\u0026rdquo; feature in a project. This naturally led us to consider using Redis\u0026rsquo; bitmap for implementation. Check-in can be done with setbit {key} {offset} 1 Cumulative check-in days can be retrieved using bitcount {key} {start} {end} index.md\nInitially, we implemented it like this: # Base date example: 2023-09-12, offset 0 for this day setbit users:id 0 1 # Binary: 10000000 # Next day, 2023-09-13, offset 1 setbit users:id 1 1 # Binary: 11000000 # Retrieving check-in days from 2023-09-12 to 2023-09-20: bitcount users:id 0 8 # Output: 2. However, testers reported issues when querying 2023-09-13 to 2023-09-20: bitcount users:id 1 7 # Output: 0. The command actually checks bits 9-16 (bytes 1-7), which are all 0s. We mistakenly assumed start and end were bit positions, but Redis versions \u0026lt;7.0 treat them as byte indexes. Workaround for Older Redis Versions Multiply the offset by 8 to avoid overlapping bits within the same byte. Although this consumes 8x more space, it simplifies the logic. setbit {key} {offset*8} 1 bitcount {key} {start} {end} Solution for Redis ≥7.0 Use the BIT parameter to specify bit-level ranges directly: bitcount {key} {start} {end} BIT ","date":"2023-09-12T21:22:58+08:00","image":"https://sethix.com/posts/2023091221/cover_hubae6115b9481d3b3f5a9cd9e375e63da_13995_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2023091221/","title":"Solution for Low Version Redis bitcount Offset Parameter Not Being Bits"},{"content":"Official steps from the documentation: https://go-zero.dev/docs/tutorials/monitor/index\nHealth Checks Name: user-api Host: 0.0.0.0 Port: 8002 DevServer: Enabled: true Port: 6470 HealthPath: \u0026#34;/healthz\u0026#34; Default health check port: 6470, default path: /healthz\nYou can use Alibaba Cloud\u0026rsquo;s Site Monitoring or similar services to periodically request this endpoint and ensure service availability.\nLog Collection Logs can be written to stdout and aggregated using services like Alibaba Cloud SLS. Distributed Tracing Integration with Alibaba Cloud ARMS: https://arms.console.aliyun.com/ 1.png Important configuration note: Do NOT select Jaeger for Batcher in go-zero\u0026rsquo;s config:\nName: xxxx # Distributed tracing configuration - use otlgrpc as other upload methods don\u0026#39;t support custom headers Telemetry: Name: xxxx Endpoint: [ARMS Endpoint] Sampler: 1.0 Batcher: otlpgrpc OtlpHeaders: Authentication: [ARMS Token] Implementation Results 2.png 3.png Metrics Monitoring Name: user-api Host: 0.0.0.0 Port: 8002 DevServer: Enabled: true Port: 6470 MetricsPath: \u0026#34;/metrics\u0026#34; EnableMetrics: true Metrics can then be collected by Prometheus or similar monitoring systems. ","date":"2023-08-31T17:50:44+08:00","image":"https://sethix.com/posts/2023083117/cover_huea45996c5d7a67599afa032e9e11b678_21141_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2023083117/","title":"Deploying Monitoring, Log Collection, and Alibaba Cloud ARMS with go-zero"},{"content":"Preface Although I started working with microservices last year and deployed them on my personal server, they were all using direct connection mode. Today I took the opportunity to upgrade the go-zero codebase and revamp the architecture. Framework I continued using go-zero (https://github.com/zeromicro/go-zero) which was originally adopted last year, just updating to the latest version.\nThe code structure features a double-layer service under the root app directory, with shared code in pkg (e.g., configuration center access) and a common Dockerfile for all services. 1.png The Dockerfile uses multi-stage builds. The build argument SERVICE_PATH specifies the target service:\ndocker build -t xxx:xx --build-arg SERVICE_PATH=${SERVICE_PATH} . FROM golang:alpine3.18 AS builder LABEL stage=gobuilder ARG SERVICE_PATH ENV CGO_ENABLED 0 RUN echo -e \u0026#39;https://mirrors.aliyun.com/alpine/v3.18/main/\\nhttps://mirrors.aliyun.com/alpine/v3.18/community/\u0026#39; \u0026gt; /etc/apk/repositories \u0026amp;\u0026amp; apk update --no-cache \u0026amp;\u0026amp; apk add --no-cache tzdata WORKDIR /build COPY . . RUN go env -w GO111MODULE=on RUN go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct RUN go mod download RUN go build -ldflags=\u0026#34;-s -w\u0026#34; -o /build/main /build/app/${SERVICE_PATH} FROM scratch ARG SERVICE_PATH COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /usr/share/zoneinfo/Asia/Shanghai ENV TZ Asia/Shanghai WORKDIR /app COPY --from=builder /build/main /app/main ENTRYPOINT [\u0026#34;./main\u0026#34;] To deploy multiple instances on a single machine without port conflicts, we dynamically assign available ports during go-zero startup: func GetAvailablePort() (int, error) { address, err := net.ResolveTCPAddr(\u0026#34;tcp\u0026#34;, \u0026#34;0.0.0.0:0\u0026#34;) if err != nil { return 0, err } listener, err := net.ListenTCP(\u0026#34;tcp\u0026#34;, address) if err != nil { return 0, err } defer listener.Close() return listener.Addr().(*net.TCPAddr).Port, nil } Service Registration \u0026amp; Discovery \u0026amp;\u0026amp; Configuration Center Key requirements for personal deployment: low cost and reliability. Service registration/discovery uses etcd. Configuration center also leverages etcd (configs pulled at startup), managed via etcdkeeper with built-in JSON/YAML support. 2.png docker-compose for infrastructure setup: version: \u0026#39;3\u0026#39; services: etcd: container_name: etcd image: bitnami/etcd:3 restart: always environment: - ETCDCTL_API=3 - ALLOW_NONE_AUTHENTICATION=yes - ETCD_ADVERTISE_CLIENT_URLS=http://127.0.0.1:2379 volumes: - \u0026#34;./data/etcd:/bitnami/etcd/data\u0026#34; network_mode: host etcdkeeper: hostname: etcdkeeper image: evildecay/etcdkeeper:v0.7.6 network_mode: host restart: always CI Using Coding for CI/CD with 10 free build hours/month. Environment variables SERVICE_PATH (build target) and SERVICE_NUMBER (instance count) are injected during builds. Deployment pseudo-code: script { def count = SERVICE_NUMBER.toInteger(); echo \u0026#34;Deploying: ${count} instances\u0026#34; for (int i = 0; i \u0026lt; count; i++) { sshCommand( remote: remoteConfig, command: \u0026#34;docker run --cpus=0.5 --memory=100m -d --net=host --restart=always --name ${SERVICE_NAME}-${i} ${IMAGE_NAME}:${CI_BUILD_NUMBER}\u0026#34;, sudo: true, ) echo \u0026#34;${SERVICE_NAME}-${i}...\u0026#34; } } 3.png End Final deployment shows multiple service instances running: 4.png ","date":"2023-08-27T11:26:42+08:00","image":"https://sethix.com/posts/2023082711/cover_hu550896a1cfadd7bf9f5c017b270e8e06_9121_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2023082711/","title":"Personal Single Server Microservices Practice"},{"content":" Official documentation provides a basic introduction. Here we\u0026rsquo;ll cover more advanced implementation details. Advanced Configuration Customizing request paths and methods hello.protobuf file syntax = \u0026#34;proto3\u0026#34;; package hello; option go_package = \u0026#34;./hello\u0026#34;; // Add import import \u0026#34;google/api/annotations.proto\u0026#34;; message Request { } message Response { string msg = 1; } service Hello { rpc Ping(Request) returns(Response) { // Add HTTP option option (google.api.http) = { post: \u0026#34;/api/v1/hello\u0026#34; body: \u0026#34;*\u0026#34; }; } } Update dependencies # Manually download annotations.proto from: # https://github.com/googleapis/googleapis/tree/master/google/api -app -hello.proto -google -api -annotations.proto -http.proto -protobuf -descriptor.proto Generate code goctl rpc protoc hello.proto --go_out=server --go-grpc_out=server --zrpc_out=server Custom errors and request headers package main import ( \u0026#34;flag\u0026#34; \u0026#34;github.com/zeromicro/go-zero/core/conf\u0026#34; \u0026#34;github.com/zeromicro/go-zero/gateway\u0026#34; ) var configFile = flag.String(\u0026#34;f\u0026#34;, \u0026#34;etc/gateway.yaml\u0026#34;, \u0026#34;config file\u0026#34;) func main() { flag.Parse() var c gateway.GatewayConf conf.MustLoad(*configFile, \u0026amp;c) gw := gateway.MustNewServer(c, withHeaders()) defer gw.Stop() // Register custom error handler httpx.SetErrorHandlerCtx(grpcErrorHandlerCtx) gw.Start() } // Process headers (remove Grpc-Metadata- prefix) func withHeaders() func(*gateway.Server) { return gateway.WithHeaderProcessor(func(header http.Header) []string { var values []string // Use protobuf enum names as keys for key := range xxx.MetaDataRequiredKey_value { values = append(values, fmt.Sprintf(\u0026#34;%s:%s\u0026#34;, key, header.Get(key))) } return values }) } // Custom error response func grpcErrorHandler(err error) (int, any) { if s, ok := status.FromError(err); ok { return http.StatusOK, Res{ Code: int(s.Code()), Msg: s.Message(), } } return http.StatusOK, Res{ Code: http.StatusInternalServerError, Msg: err.Error(), } } func grpcErrorHandlerCtx(ctx context.Context, err error) (int, any) { return grpcErrorHandler(err) } type Res struct { Code int `json:\u0026#34;code\u0026#34;` Msg string `json:\u0026#34;msg\u0026#34;` } More Default protobuf generation doesn\u0026rsquo;t include HTTP method/path definitions. A PR adds default POST method and RPC method name as API path. Gateway headers require Grpc-Metadata- prefix when passed to RPC services. ","date":"2023-08-16T18:51:21+08:00","image":"https://sethix.com/posts/2023081618/cover_hu5a627bd7e284c53156e8d94692ebf836_37856_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2023081618/","title":"Building APIs Quickly with go-zero and gRPC Gateway"},{"content":"Background We previously encountered an issue where the service completely crashed when MySQL went down, with Redis failing to handle any requests. The normal business query logic is: Get data from Redis first, return if available If Redis has no data, query MySQL Write the retrieved data to Redis Return data Problem Analysis Redis itself wasn\u0026rsquo;t the issue - the problem occurred at step 2 When querying MySQL with the database service down, requests get blocked Blocking timeout leads to exceptions, preventing step 3 from executing Subsequent requests continue trying to connect to MySQL, creating infinite blocking that overloads the application servers Solution Our solution (may not fit all scenarios): Force caching empty data in Redis when MySQL crashes, allowing partial empty responses instead of service failure Implementation Approach Set appropriate MySQL connection timeout mysqlnd.net_read_timeout = 3 Throw exceptions on connection timeout Create a BaseModel that other models extend, overriding newEloquentBuilder \u0026lt;?php namespace App\\Models; use Illuminate\\Database\\Eloquent\\Model; class BaseModel extends Model { public function newEloquentBuilder($query) { return new MysqlCustomBuilder($query); } } Create a custom query builder MysqlCustomBuilder \u0026lt;?php namespace App\\Models\\Database; use Illuminate\\Database\\Eloquent\\Builder; use Illuminate\\Database\\Eloquent\\Collection; use Illuminate\\Support\\Facades\\Log; use Illuminate\\Support\\Str; class MysqlCustomBuilder extends Builder { public function get($columns = [\u0026#39;*\u0026#39;]) { try { return parent::get($columns); } catch (\\Exception $e) { // Handle Laravel\u0026#39;s reconnection error codes $message = $e-\u0026gt;getMessage(); if (Str::contains($message, [ \u0026#39;server has gone away\u0026#39;, \u0026#39;no connection to the server\u0026#39;, \u0026#39;Lost connection\u0026#39;, \u0026#39;is dead or not enabled\u0026#39;, \u0026#39;Error while sending\u0026#39;, \u0026#39;decryption failed or bad record mac\u0026#39;, \u0026#39;server closed the connection unexpectedly\u0026#39;, \u0026#39;SSL connection has been closed unexpectedly\u0026#39;, \u0026#39;Error writing data to the connection\u0026#39;, \u0026#39;Resource deadlock avoided\u0026#39;, ])) { // Log error and notify // Log::error($e); // Force return empty collection return Collection::make(); } throw $e; } } } Implement strict monitoring of error logs to distinguish between empty responses caused by configuration issues vs database failures ","date":"2023-06-25T14:14:01+08:00","image":"https://sethix.com/posts/2023062514/cover_hu7c171dafd19091c52f5acb8c61d562d1_9381_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2023062514/","title":"Force Returning Empty Data When MySQL Unexpectedly Crashes in Laravel"},{"content":"Documentation: https://help.aliyun.com/document_detail/383953.html?spm=a2c4g.383947.0.0.47607d9dnkBjdG\nCode Implementation \u0026lt;!DOCTYPE html\u0026gt; \u0026lt;html lang=\u0026#34;en\u0026#34;\u0026gt; \u0026lt;head\u0026gt; \u0026lt;meta charset=\u0026#34;UTF-8\u0026#34;/\u0026gt; \u0026lt;title\u0026gt;Document\u0026lt;/title\u0026gt; \u0026lt;/head\u0026gt; \u0026lt;body\u0026gt; \u0026lt;input type=\u0026#34;file\u0026#34; id=\u0026#34;file\u0026#34;\u0026gt; \u0026lt;span id=\u0026#34;process\u0026#34;\u0026gt;\u0026lt;/span\u0026gt; \u0026lt;button id=\u0026#34;submit\u0026#34;\u0026gt;Resume Upload\u0026lt;/button\u0026gt; \u0026lt;!-- Import SDK --\u0026gt; \u0026lt;script type=\u0026#34;text/javascript\u0026#34; src=\u0026#34;https://gosspublic.alicdn.com/aliyun-oss-sdk-6.16.0.min.js\u0026#34; \u0026gt;\u0026lt;/script\u0026gt; \u0026lt;script type=\u0026#34;text/javascript\u0026#34;\u0026gt; // Use multiple clients for multi-file uploads const client = new OSS({ // Replace yourRegion with actual region code region: \u0026#39;yourRegion\u0026#39;, // Get from STS service accessKeyId: \u0026#39;yourAccessKeyId\u0026#39;, accessKeySecret: \u0026#39;yourAccessKeySecret\u0026#39;, stsToken: \u0026#39;yourSecurityToken\u0026#39;, bucket: \u0026#34;examplebucket\u0026#34;, }); // Define checkpoint for resume let abortCheckpoint; // Get DOM elements let uploadFile; const process = document.getElementById(\u0026#34;process\u0026#34;); const file = document.getElementById(\u0026#34;file\u0026#34;); const submit = document.getElementById(\u0026#34;submit\u0026#34;); // File selection handler file.addEventListener(\u0026#39;change\u0026#39;, function () { uploadFile = this.files[0]; // Generate unique ID (recommend using MD5 hash) uploadFile.id = \u0026#39;\u0026#39; + uploadFile.size + uploadFile.name; uploadFile.checkpoint = getData(uploadFile); // Display progress if (uploadFile.checkpoint) { process.innerText = uploadFile.checkpoint.process + \u0026#39;%\u0026#39;; } else { process.innerText = \u0026#39;No resume data\u0026#39;; } }); // Upload button handler submit.addEventListener(\u0026#34;click\u0026#34;, function () { if (!uploadFile) { alert(\u0026#39;No file selected\u0026#39;); return; } let filename = uploadFile.id; let checkpointData = uploadFile.checkpoint; // Handle existing checkpoint if (checkpointData) { if (checkpointData.process === 100) { // Upload completed, submit to backend // deleteData(uploadFile); return; } checkpointData.file = uploadFile; } // Initiate multipart upload client .multipartUpload(filename, uploadFile, { progress: (p, checkpoint, res) =\u0026gt; { let processVal = Math.round(p * 100); process.innerText = processVal + \u0026#39; %\u0026#39;; // Update progress checkpoint.process = processVal; setData(uploadFile, checkpoint); }, // 100KB chunks for demo partSize: 1024 * 100, checkpoint: checkpointData, }) .then(function (r) { console.log(r); // Cleanup after completion deleteData(uploadFile); }); }); // Local storage helpers function getData(file) { let data = JSON.parse(window.localStorage.getItem(file.id)); return data ? data : null; } function setData(file, checkpoint) { const storageData = { file: null, name: checkpoint.name, fileSize: checkpoint.fileSize, partSize: checkpoint.partSize, uploadId: checkpoint.uploadId, doneParts: checkpoint.doneParts, process: checkpoint.process }; window.localStorage.setItem(file.id, JSON.stringify(storageData)); } function deleteData(file) { window.localStorage.removeItem(file.id); } \u0026lt;/script\u0026gt; \u0026lt;/body\u0026gt; \u0026lt;/html\u0026gt; Key Features Resumable Uploads: Stores upload progress in localStorage Progress Tracking: Real-time percentage display Chunk Upload: 100KB chunks for better reliability Checkpoint Management: Automatic resume from last successful chunk Implementation Notes Uses browser\u0026rsquo;s localStorage for checkpoint persistence Requires valid OSS credentials (AccessKey/STS Token) File identification uses size+name combination (MD5 recommended for production) Cleanup completed uploads automatically ","date":"2023-04-27T11:09:55+08:00","image":"https://sethix.com/posts/2023042711/cover_hu53e9daddee4a032720607a1fc1d44a82_8841_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2023042711/","title":"Implementation of OSS Browser Refresh and Resumable Upload Feature"},{"content":"Introduction Spent a day upgrading the architecture of Youmengji from Flutter 2 to Flutter 3. Here\u0026rsquo;s a summary of the pitfalls encountered.\nUpgrading Flutter Version Check current version:\nflutter --version Upgrade Flutter (requires VPN access):\nflutter upgrade Verify version (should start with 3.x):\nflutter --version If you\u0026rsquo;re lucky enough to run the app directly after this, you can stop reading here.\ncompileSdkVersion Error Modify compileSdkVersion to 33 in android/app/build.gradle Update distributionUrl in android/gradle/wrapper/gradle-wrapper.properties: distributionUrl=https\\://services.gradle.org/distributions/gradle-7.4-all.zip Update Gradle plugin in android/build.gradle: classpath \u0026#39;com.android.tools.build:gradle:7.1.2\u0026#39; Update SDK via Android Studio\u0026rsquo;s SDK Manager: 1.png 2.png Warning: Mapping new ns xxx to old ns xxx Modify repository URLs in android/build.gradle: // From: maven { url \u0026#39;http://maven.aliyun.com/nexus/content/groups/public\u0026#39; } // To: maven { url \u0026#39;https://maven.aliyun.com/repository/public\u0026#39; } Error: No named parameter with the name \u0026lsquo;maxLengthEnforced\u0026rsquo; Common issue with deprecated parameters after Flutter upgrades. Solution: Update all dependencies to their latest versions Follow migration guides for breaking changes in SDKs No signature of method: .android() in build.gradle (app) Remove useProguard configuration in android/app/build.gradle: buildTypes { release { minifyEnabled true // Delete this line proguardFiles getDefaultProguardFile(\u0026#39;proguard-android.txt\u0026#39;), \u0026#39;proguard-rules.pro\u0026#39; } } JAR Version Conflict Warning Ensure Kotlin version consistency: ext.kotlin_version = \u0026#39;1.7.10\u0026#39; dependencies { classpath \u0026#39;com.android.tools.build:gradle:7.2.0\u0026#39; classpath \u0026#34;org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\u0026#34; } Pro tip: Create a new Flutter project (flutter new app) to compare with fresh configuration files. ","date":"2023-02-25T21:55:31+08:00","image":"https://sethix.com/posts/2023022521/cover_hu9f07d342ff0579eaa758e310d352a662_6564_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2023022521/","title":"Upgrading from Flutter 2 to Flutter 3"},{"content":"Context The test environment database resides in an internal network, while my computer can only connect via a jump server. To enable local code access, I tested MobaXterm for SSH tunneling.\nInstallation Download the free version from the official site: https://mobaxterm.mobatek.net/download.html 1.png Choose between the portable version (no installation) or installer. I selected the installer for straightforward setup. 2.png Configuration Open MobaXterm, navigate to Tunneling \u0026gt; New SSH tunnel 3.png Configure three key sections: ① Internal database server IP/port ② Jump server SSH credentials (IP, user, port) ③ Local port (choose an unused port) 4.png Click the key icon to configure SSH key authentication for the jump server. Restart tunnels via Stop all tunnels \u0026gt; Start all tunnels to apply changes. 5.png Verification Check port forwarding status:\n# Check port 3306 listening status netstat -ano | findstr \u0026#34;3306\u0026#34; TCP 0.0.0.0:3306 0.0.0.0:0 LISTENING 18356 TCP [::]:3306 [::]:0 LISTENING 18356 # Test MySQL service connectivity telnet 127.0.0.1 3306 N 5.7.22-log [xxx]mysql_native_password # Random characters indicate successful tunneling Update database connection string to:\nmysql:username:password@tcp(127.0.0.1:3306)/database\nThis method also works for Redis and other internal services. Xshell Configuration Similar process applies to Xshell: 6.png ","date":"2023-02-08T14:50:58+08:00","image":"https://sethix.com/posts/2023020814/cover_hu9d3f35e1c1c22a210009db94cf297f7b_9794_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2023020814/","title":"Accessing Internal Network MySQL Database Locally via MobaXterm Xshell Tunneling"},{"content":" My desktop PC is under the desk with a keyboard drawer, requiring me to bend down for power operations - quite inconvenient Purchased a PCI-E power control card (Taobao price: ¥35). Confirm your motherboard has compatible PCI-E slot (shown below) If unsure about motherboard compatibility, send your motherboard photo to customer service for verification\n1.jpg Getting Started The power control card as received:\n2.jpg Motherboard header diagram (key point: locate the POWER SW pins in bottom-right corner)\n3.jpg Installation steps:\n1. Connect original POWER SW cable to the control card\n2. Connect control card\u0026rsquo;s POWER SW cable to motherboard header\n3. Insert control card into PCI-E slot\nImportant: Always unplug power cable before installation to prevent accidental boot\n4.jpg Mi Home Setup The control card auto-appears in Mi Home app after PC boots. Rename device to \u0026ldquo;Computer\u0026rdquo; in app.\n5.jpg Demo ","date":"2023-02-07T20:19:01+08:00","image":"https://sethix.com/posts/2023020720/cover_huf2f677795ee8db36a3678ac902eebfa5_65299_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2023020720/","title":"Xiaoai Assistant + Remote PC Power Control"},{"content":"Explanation Many concepts in this article reference insights from Sensors Data documentation. Attribution Methods Self-Attribution\nTracked by ad platforms. Some platforms receive app-open callbacks from users and perform attribution internally. Others like Huawei store attribution data locally during app installation, retrievable during first launch. Impression Attribution\nRarely used due to massive data volumes. Click Attribution (Most Common)\nAttributes conversions to the last ad click before conversion. Attribution Models Last-Touch Model (Most Common)\n100% credit to the final touchpoint before conversion. First-Touch Model\n100% credit to the initial touchpoint that introduced the user. Linear Model\nEqual credit distribution across all touchpoints. Time-Decay Model\nHigher weight given to more recent interactions. Position-Based Model\n40% credit to first/last touchpoints, 20% distributed among others. Custom Weighted Model\nCustom weights assigned to different channels. Matching Methods Exact Matching\nUses device identifiers: OAID, AndroidID, IMEI, MAC. Fuzzy Matching\nUses IP addresses and User-Agent strings. Architecture Implementation Architecture Diagram Core Database Schema -- Applications Table (apps) id, appid, name, os, attribute_cycle_days, attribute_white_list(JSON) -- Channels Table (channels) id, name, template_query -- Tracking Links Table (links) id, app_id, channel_id, channel_name, events(JSON), exp -- Click Logs Table (click_logs, daily partitioned) id, appid, ad_name, oaid, imei, android_id, mac, ip, ua, exp, callback, data(JSON), attributed_at -- Attribution Logs \u0026amp; Callback Logs (custom logging) Key Workflows 1. Ad Click Tracking (Endpoint) // Unified request structure class AdClickRequest { public $oaid; public $imei; public $imei_md5; public $android_md5; public $ad_name; public $callback; } // Simplified endpoint logic function clickLogs($id) { // 1. Parse request $req = new AdClickRequest(/* input params */); // 2. Validate tracking link $link = DB::table(\u0026#39;links\u0026#39;)-\u0026gt;find($id); if (!$link) return response(\u0026#39;FAIL\u0026#39;, 400); // 3. Insert click log (async via queue) $log = ClickLog::create([ \u0026#39;oaid\u0026#39; =\u0026gt; $req-\u0026gt;oaid, \u0026#39;imei\u0026#39; =\u0026gt; $req-\u0026gt;imei_md5, \u0026#39;events\u0026#39; =\u0026gt; $link-\u0026gt;events, \u0026#39;exp\u0026#39; =\u0026gt; $link-\u0026gt;exp ]); // 4. Cache identifiers for attribution window Redis::pipeline(function($pipe) use ($link, $req) { foreach ([\u0026#39;oaid\u0026#39;,\u0026#39;imei_md5\u0026#39;,\u0026#39;android_md5\u0026#39;] as $field) { $key = \u0026#34;attr:{$link-\u0026gt;app_id}_{$req-\u0026gt;$field}\u0026#34;; $pipe-\u0026gt;setex($key, $link-\u0026gt;exp*86400, \u0026#34;{$log-\u0026gt;id}:{$log-\u0026gt;table}\u0026#34;); } }); return response(\u0026#39;OK\u0026#39;); } 2. First Launch Attribution class AppReportRequest { public $device_key; public $oaid; public $imei; public $mac; } function appReport($appId) { // 1. Parse device data $req = new AppReportRequest(/* input */); // 2. Check cached click logs $matchedLog = null; foreach ([\u0026#39;oaid\u0026#39;,\u0026#39;imei\u0026#39;,\u0026#39;mac\u0026#39;] as $field) { $key = \u0026#34;attr:{$appId}_{$req-\u0026gt;$field}\u0026#34;; $logInfo = Redis::get($key); if ($logInfo) { [$logId, $table] = explode(\u0026#39;:\u0026#39;, $logInfo); $matchedLog = DB::table($table)-\u0026gt;find($logId); break; } } if (!$matchedLog) return response(\u0026#39;No attribution\u0026#39;, 404); // 3. Record attribution Redis::setex(\u0026#34;attr_device:{$appId}_{$req-\u0026gt;device_key}\u0026#34;, 604800, $matchedLog-\u0026gt;id); // 4. Cleanup \u0026amp; async callbacks Redis::del(array_keys($matchedKeys)); Queue::dispatch(new ProcessAttribution($matchedLog)); return response(\u0026#39;OK\u0026#39;); } 3. Event Callbacks function eventCallback($appId, $event, $deviceKey) { $logId = Redis::get(\u0026#34;attr_device:{$appId}_{$deviceKey}\u0026#34;); $log = ClickLog::find($logId); // Validate event against link configuration if (in_array($event, json_decode($log-\u0026gt;events))) { // Execute channel-specific callback template Http::post($log-\u0026gt;callback, [ \u0026#39;event\u0026#39; =\u0026gt; $event, \u0026#39;params\u0026#39; =\u0026gt; $log-\u0026gt;data ]); } return response(\u0026#39;Processed\u0026#39;); } Debugging Tools 1. Device Attribution Checker Debug Interface Input device identifiers to simulate attribution matching.\n2. Real-time Click Log Monitoring Click Log Verification Verify if click logs are received from ad platforms.\n3. Attribution Whitelisting Whitelist Management Bypass attribution rules for testing specific devices.\n4. Event Callback Testing Event Callback Debug Manually trigger and verify postback events.\nClient Implementation // Unified attribution handler class AttributionTracker { constructor() { this.storageKey = \u0026#39;attribution_events\u0026#39;; } track(event) { const sentEvents = this._getSentEvents(); if (sentEvents[event]) return; api.post(\u0026#39;/callback\u0026#39;, { event }).then(() =\u0026gt; { sentEvents[event] = true; this._saveEvents(sentEvents); }); } attributeLaunch() { api.post(\u0026#39;/launch\u0026#39;).then(() =\u0026gt; { this._clearSentEvents(); }); } _getSentEvents() { return JSON.parse(localStorage.getItem(this.storageKey)) || {}; } _saveEvents(events) { localStorage.setItem(this.storageKey, JSON.stringify(events)); } _clearSentEvents() { localStorage.removeItem(this.storageKey); } } This architecture provides:\nModular Design: Separates click tracking, attribution matching, and callback execution. Scalable Storage: Uses partitioned tables and Redis for high-frequency operations. Flexible Matching: Supports both exact and fuzzy matching strategies. Debuggability: Comprehensive tools for platform verification and testing. ","date":"2023-01-12T14:58:55+08:00","image":"https://sethix.com/posts/2023011214/cover_hueefab3b38845db3c274bd17e914b1f26_47928_120x120_fill_q75_box_smart1.jpeg","permalink":"https://sethix.com/posts/2023011214/","title":"Advertising Attribution - A Comprehensive Guide to Attribution Architecture Implementation"},{"content":"Overview The terms \u0026ldquo;Continuous Monthly Subscription\u0026rdquo;, \u0026ldquo;Periodic Deduction\u0026rdquo;, and \u0026ldquo;Auto-Renewal\u0026rdquo; refer to the same core functionality:\nPeriodic Deduction - Official Alipay terminology Continuous Monthly Subscription - Common implementation pattern (also supports daily/quarterly) Auto-Renewal - User-facing behavior of automatic payment Deduction Scenarios Two implementation models:\nSign-then-Deduct\nRedirect to agreement signing page User signs agreement Alipay async callback + immediate deduction Pay-then-Sign\nRedirect to payment page (user can disable auto-renewal) User completes payment Receive two async notifications: payment \u0026amp; agreement Recommendation: Prefer Sign-then-Deduct to prevent users from disabling renewal during payment.\nPlatform Requirements Alipay: Requires enabling \u0026ldquo;Periodic Deduction\u0026rdquo; via Alipay Open Platform WeChat Pay: More complex application process requiring additional Template ID Agreement Signing Flow Signature Generation (Go Implementation) We use modified gopay library (PR #295 merged 2023-01-01):\nKey implementation notes:\nGenerate contract_code as merchant agreement ID Create signature parameters for mobile app deep linking: // Example signature parameters bm := gopay.BodyMap{} bm.Set(\u0026#34;personal_product_code\u0026#34;, \u0026#34;GENERAL_WITHHOLDING\u0026#34;) bm.Set(\u0026#34;sign_scene\u0026#34;, \u0026#34;INDUSTRY|OTHER\u0026#34;) bm.Set(\u0026#34;external_agreement_no\u0026#34;, contractCode) // ... other required fields Construct deep link URL: alipays://platformapi/startapp?appId=60000157\u0026amp;sign_params={URL-Encoded_Params} Database Design Core subscription table structure (simplified):\nCREATE TABLE subscriptions ( id INT PRIMARY KEY, order_no VARCHAR(64) UNIQUE, -- Merchant order ID trade_no VARCHAR(64), -- Payment platform ID user_id INT, -- User reference contract_code VARCHAR(64) UNIQUE, -- Custom agreement ID contract_id VARCHAR(64), -- Platform agreement ID expire_time DATETIME -- Next deduction date ); Order Processing Flow Create order with generated contract_code Generate signing parameters and return deep link to client Handle async notification to store contract_id Initial payment via alipay.trade.pay (synchronous API) Client polling for payment status Scheduled task for recurring deductions: // Cron job example (executed daily) func CheckSubscriptions() { // Query subscriptions expiring in 5 days subscriptions := GetExpiringSubscriptions() for _, sub := range subscriptions { // Initiate payment via Alipay API resp, err := alipay.TradePay(sub) // Handle payment result } } Platform-Specific Notes Platform Deduction Lead Time Example Timeline WeChat 2 days Sign 15th → Deduct 13th → Result 15th Alipay 5 days Sign 15th → Deduct 10th → Result 15th Key Implementation Points Use separate async handlers for payment \u0026amp; agreement notifications Implement idempotency checks for all payment operations Maintain detailed audit logs for deduction attempts Provide clear cancellation UI/API endpoints Complete implementation example available at: github.com/yourrepo/subscription-service\n","date":"2022-12-29T14:45:32+08:00","image":"https://sethix.com/posts/2022122914/cover_hub76e9b76e4d5acaefa75ae9c0d11e2cd_108552_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022122914/","title":"Continuous Monthly Subscription - Periodic Deduction - Auto-Renewal Business Process Summary"},{"content":"Recently I\u0026rsquo;ve been busy integrating third-party advertising platforms. During this process, I noticed that some API documentation was simply provided as Word documents with hundreds of parameters listed in tables, requiring manual parameter construction - a truly tedious process.\nHowever, several providers stood out by offering .proto files, allowing automatic generation of Request and Response structures through protobuf - a developer-friendly approach worth applauding!\nKey Takeaways When integrating APIs, always ask business partners if protobuf schema files are available Generate Go code using: protoc pb\\xxx.proto --go_out=. This automatically creates ready-to-use request/response structures, enums, etc., significantly streamlining backend integration (a pattern worth adopting for future backend interfaces) Sample Implementation package main import ( \u0026#34;bytes\u0026#34; \u0026#34;io/ioutil\u0026#34; \u0026#34;log\u0026#34; \u0026#34;net/http\u0026#34; \u0026#34;github.com/golang/protobuf/proto\u0026#34; \u0026#34;xxxx/internal/pb\u0026#34; ) func main() { getDataByAdServe() } func getDataByAdServe() { // Serialize request data r := \u0026amp;pb.AdProfRequest{} data, er := proto.Marshal(r) if er != nil { log.Fatal(er) return } // Send HTTP request (set proper timeout in production) reader := bytes.NewReader(data) resp, err := http.Post(\u0026#34;http://127.0.0.1:8001/xxx\u0026#34;, \u0026#34;application/x-protobuf\u0026#34;, reader) if err != nil { log.Println(err) return } defer resp.Body.Close() // Read response body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Println(err) return } // Deserialize response var res pb.AdProfResponse if err := proto.Unmarshal(body, \u0026amp;res); err != nil { log.Println(err) return } log.Println(\u0026amp;res) } This implementation demonstrates:\nProtobuf serialization/deserialization HTTP communication with protobuf payloads Proper error handling and resource cleanup The application/x-protobuf Content-Type header ensures servers correctly interpret the binary payload. For production use, consider adding request timeouts and retry mechanisms.\n","date":"2022-10-12T11:00:46+08:00","image":"https://sethix.com/posts/2022101211/cover_huf1e81f4a05192c69f29b234236a98ea2_8920_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022101211/","title":"Using Protobuf Protocol Data in HTTP Requests"},{"content":"Recently, I\u0026rsquo;ve been working on integrating third-party advertising bidding services. Most advertising platforms with bidding capabilities encrypt their bid prices using the AES algorithm.\nWhen integrating with third parties, challenges arise due to varying encryption modes and the lack of SDKs (some only provide Java client code examples). Here are some practical approaches:\nUse third-party validation tools like https://tool.lmeee.com/jiami/aes for cross-verification Analyze Java code to identify critical encryption parameters: Encryption Mode (ECB, CBC, CFB, OFB) Padding Method (pkcs5padding, pkcs7padding, zeropadding) Key Length (128-bit/8-char key, 192-bit/12-char key, 256-bit/16-char key) IV (Initialization Vector - some require random values, others use fixed values) Base64UrlSafe Encoding requirement for ciphertext Practical Observations: ECB Dominance: Many platforms use ECB mode for simplicity despite security risks, as it requires only a key (no IV). CFB Implementation: Zhimeng (知盟) uses CFB with random keys but doesn\u0026rsquo;t validate IV parameters. CBC with Fixed IV: RuanGaoyun (软告云) employs CBC mode but reuses the key as IV for simplicity. Pro Tip: Always verify if platforms require URL-safe Base64 encoding for encrypted payloads. This subtle requirement is a common integration pitfall.\n","date":"2022-09-07T16:52:05+08:00","image":"https://sethix.com/posts/2022090716/cover_hu620fac4d17d87c0e43ec32bf387c48d3_33431_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022090716/","title":"Application of AES Encryption Algorithm"},{"content":"The short answer: It depends on your configuration and implementation.\nToday I saw an interesting question in the community:\nWhy does PHP handle file uploads using move_uploaded_file to move a pre-uploaded file, rather than reading the file content directly from the HTTP Body?\nThis question intrigued me. After researching, I found an analysis of PHP file upload implementation (RFC1867) by Laruence (Bird Brother), but it didn\u0026rsquo;t fully explain the reason. So I decided to examine Go\u0026rsquo;s file upload implementation. Go Implementation In Go, retrieving uploaded files is straightforward using http.Request.FormFile: package main import ( \u0026#34;log\u0026#34; \u0026#34;net/http\u0026#34; ) func main() { http.HandleFunc(\u0026#34;/files\u0026#34;, func(writer http.ResponseWriter, request *http.Request) { // 32MB memory limit err := request.ParseMultipartForm(32 \u0026lt;\u0026lt; 20) if err != nil { log.Println(err) return } // Get uploaded file file, handler, err := request.FormFile(\u0026#34;file_key\u0026#34;) log.Println(file, handler, err) }) if err := http.ListenAndServe(\u0026#34;:8000\u0026#34;, nil); err != nil { log.Println(err) } } The implementation of http.Request.FormFile is simple - it retrieves data from a map. The core logic resides in http.Request.ParseMultipartForm: func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error) { if r.MultipartForm == multipartByReader { return nil, nil, errors.New(\u0026#34;http: multipart handled by MultipartReader\u0026#34;) } if r.MultipartForm == nil { err := r.ParseMultipartForm(defaultMaxMemory) if err != nil { return nil, nil, err } } if r.MultipartForm != nil \u0026amp;\u0026amp; r.MultipartForm.File != nil { if fhs := r.MultipartForm.File[key]; len(fhs) \u0026gt; 0 { f, err := fhs[0].Open() return f, fhs[0], err } } return nil, nil, ErrMissingFile } The http.Request.ParseMultipartForm method calls multipart.Reader.ReadForm to parse the request body. Key observations: File storage (memory vs disk) depends on whether the total size exceeds the maxMemory parameter. Form values count against a separate 10MB allowance within maxMemory. If content exceeds maxMemory, files are written to temporary storage (similar to PHP\u0026rsquo;s approach). func (r *Reader) readForm(maxMemory int64) (_ *Form, err error) { // ... (initialization omitted) // Reserve 10MB for non-file parts maxValueBytes := maxMemory + int64(10\u0026lt;\u0026lt;20) for { p, err := r.NextPart() // ... (error handling omitted) if filename == \u0026#34;\u0026#34; { // Handle form values io.CopyN(\u0026amp;b, p, maxValueBytes+1) // ... } else { // Handle file upload n, err := io.CopyN(\u0026amp;b, p, maxMemory+1) if n \u0026gt; maxMemory { // Write to temp file when exceeding memory limit file, err := os.CreateTemp(\u0026#34;\u0026#34;, \u0026#34;multipart-\u0026#34;) // ... io.Copy(file, io.MultiReader(\u0026amp;b, p)) } else { // Store in memory fh.content = b.Bytes() } } } return form, nil } Key Takeaways Memory usage depends on your configured maxMemory and actual file sizes Files exceeding maxMemory get streamed to temporary files The request body is read sequentially - you can\u0026rsquo;t skip file processing Why Can\u0026rsquo;t We Skip File Processing? HTTP bodies are parsed sequentially Files might appear at any position in the multipart data The server must process each part in order, even for large files PS: In Go, the Request.Body can only be read once due to its streaming nature.\n","date":"2022-07-01T11:45:13+08:00","image":"https://sethix.com/posts/2022070111/cover_hu7dfdeebea5a4bd05e0dc2aa5728b62d5_15818_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022070111/","title":"Does Uploading a 10MB File in Go Really Use 10MB of Memory?"},{"content":" With service registration and discovery mechanisms, consumers don\u0026rsquo;t need to know the actual physical addresses of service providers to make calls, nor do they need to know how many providers are available. Service providers simply register with the registry to expose their services, without needing to know which specific services are consuming them.\nRPC Configuration Name: user.rpc ListenOn: 0.0.0.0:8081 Etcd: Hosts: - 127.0.0.1:2379 Key: user.rpc Analyzing the etcd-related source code in go-zero. Source reference: https://github.com/zeromicro/go-zero-demo/tree/master/mall Callee - Service Registration Source code at mall/user/rpc/user.go: package main import ( \u0026#34;flag\u0026#34; \u0026#34;fmt\u0026#34; \u0026#34;go-zero-demo-rpc/mall/user/rpc/internal/config\u0026#34; \u0026#34;go-zero-demo-rpc/mall/user/rpc/internal/server\u0026#34; \u0026#34;go-zero-demo-rpc/mall/user/rpc/internal/svc\u0026#34; \u0026#34;go-zero-demo-rpc/mall/user/rpc/types/user\u0026#34; \u0026#34;github.com/zeromicro/go-zero/core/conf\u0026#34; \u0026#34;github.com/zeromicro/go-zero/core/service\u0026#34; \u0026#34;github.com/zeromicro/go-zero/zrpc\u0026#34; \u0026#34;google.golang.org/grpc\u0026#34; \u0026#34;google.golang.org/grpc/reflection\u0026#34; ) var configFile = flag.String(\u0026#34;f\u0026#34;, \u0026#34;etc/user.yaml\u0026#34;, \u0026#34;the config file\u0026#34;) func main() { flag.Parse() var c config.Config conf.MustLoad(*configFile, \u0026amp;c) ctx := svc.NewServiceContext(c) svr := server.NewUserServer(ctx) s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { user.RegisterUserServer(grpcServer, svr) if c.Mode == service.DevMode || c.Mode == service.TestMode { reflection.Register(grpcServer) } }) defer s.Stop() fmt.Printf(\u0026#34;Starting rpc server at %s...\\n\u0026#34;, c.ListenOn) s.Start() } The MustNewServer internally calls NewServer, which creates an internal.Server instance via internal.NewRpcPubServer if c.HasEtcd() { server, err = internal.NewRpcPubServer(c.Etcd, c.ListenOn, serverOptions...) if err != nil { return nil, err } } internal.NewRpcPubServer func NewRpcPubServer(etcd discov.EtcdConf, listenOn string, opts ...ServerOption) (Server, error) { registerEtcd := func() error { pubListenOn := figureOutListenOn(listenOn) // ... etcd configuration handling pubClient := discov.NewPublisher(etcd.Hosts, etcd.Key, pubListenOn, pubOpts...) return pubClient.KeepAlive() } // ... server initialization } figureOutListenOn resolves the actual registration address: Handles special cases for 0.0.0.0 Retrieves internal IP if needed func figureOutListenOn(listenOn string) string { // ... address resolution logic } The registration process in Publisher.KeepAlive(): Creates etcd lease Registers service with key:value format Maintains keep-alive heartbeat func (p *Publisher) KeepAlive() error { // ... etcd client initialization // ... lease management return p.keepAliveAsync(cli) } Registered service example in etcd: 1.png Caller - Service Discovery Caller code at order/api/order.go: package main import ( \u0026#34;flag\u0026#34; \u0026#34;fmt\u0026#34; \u0026#34;go-zero-demo-rpc/order/api/internal/config\u0026#34; \u0026#34;go-zero-demo-rpc/order/api/internal/handler\u0026#34; \u0026#34;go-zero-demo-rpc/order/api/internal/svc\u0026#34; \u0026#34;github.com/zeromicro/go-zero/core/conf\u0026#34; \u0026#34;github.com/zeromicro/go-zero/rest\u0026#34; ) var configFile = flag.String(\u0026#34;f\u0026#34;, \u0026#34;etc/order.yaml\u0026#34;, \u0026#34;the config file\u0026#34;) func main() { flag.Parse() var c config.Config conf.MustLoad(*configFile, \u0026amp;c) server := rest.MustNewServer(c.RestConf) defer server.Stop() ctx := svc.NewServiceContext(c) handler.RegisterHandlers(server, ctx) fmt.Printf(\u0026#34;Starting server at %s:%d...\\n\u0026#34;, c.Host, c.Port) server.Start() } Service discovery initialization via zrpc.MustNewClient: Builds etcd-based target format discov://{hosts}/{serviceKey} Implements resolver watching etcd changes func (b *discovBuilder) Build(target resolver.Target, cc resolver.ClientConn, _ resolver.BuildOptions) ( resolver.Resolver, error) { // ... etcd subscriber initialization sub.AddListener(update) update() return \u0026amp;nopResolver{cc: cc}, nil } Discovery process details: Initial load of available endpoints Continuous etcd watch for changes Dynamic endpoint list updates func (c *cluster) monitor(key string, l UpdateListener) error { // ... etcd client initialization c.load(cli, key) c.watch(cli, key) } Discovered service endpoints in etcd: 2.png Q\u0026amp;A Q: Why not use Redis as registry?\nA: Key reasons include:\nLack of versioning support Unsuitable pub/sub implementation for production Higher latency compared to etcd\u0026rsquo;s watch Different clustering approaches (Raft vs Redis Cluster) Data persistence differences Reference: https://www.v2ex.com/t/520367 ","date":"2022-06-15T18:13:30+08:00","image":"https://sethix.com/posts/2022061518/cover_hub7e19524e7bff55e07eaa0723081c1ad_4008_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022061518/","title":"Service Registration and Discovery in Microservices"},{"content":" Following the previous Redis incident, our monitoring system recently alerted about abnormal MySQL load in the advertising system The Ops team asked me to investigate whether recent code changes caused the database load spike. As shown: Database The graph clearly shows a sudden load surge at the marked timestamp, which persisted without subsiding Checking Git commit history revealed no deployments on that day, indicating operational configuration changes might be the culprit Accessed Alibaba Cloud\u0026rsquo;s SQL Audit and Analysis feature (similar solutions exist on other cloud platforms): SQL Audit The problematic SQL query was quickly identified, accounting for over 90% of total queries Next steps were straightforward: Locate the corresponding code for this SQL Root cause analysis: Original code handled single configurations, but recent operational changes allowed multiple options No caching implementation Optimized query logic and added caching mechanisms Database Database Post-optimization showed reduced database load, but another SQL query became prominent with higher average latency due to WHERE EXISTS usage: The Laravel whereHas method generated inefficient WHERE EXISTS queries GitHub solutions suggested using WHERE IN instead Implemented custom solution using these patterns (alternative packages available): laravel-wherehasin hasin eloquent-has-by-non-dependent-subquery Database Database Final optimizations resulted in: Balanced query distribution Database load reduced to 1% (compared to ~50% previously) Consistent performance during peak periods ","date":"2022-06-09T16:59:31+08:00","image":"https://sethix.com/posts/2022060916/cover_hu1925a3d44a75eb991deafaf920175d43_8914_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022060916/","title":"Optimizing Database Queries to Reduce MySQL Load to 1%"},{"content":" A side note: The article description was auto-generated using https://copilot.github.com/. This tool is indeed very useful, everyone should give it a try. (The gray text in the image shows its auto-generated suggestions, press Tab to accept them) 1.png Preface In China, except for Huawei AppGallery, other app stores don\u0026rsquo;t allow individual developers to upload applications. Therefore, we decided to publish on Google Play. Initially when developing YouMengji, we didn\u0026rsquo;t consider internationalization and hardcoded all UI text. After continuous efforts in bug fixing, we implemented full internationalization (including server-side), allowing users to select their preferred language. Publishing Process Requires a computer that can access https://play.google.com/ A $25 USD fee is required for Google Play developer account registration. Consider using Taobao agent services for payment. Apps must be uploaded in aab format: https://developer.android.com/guide/app-bundle/faq?hl=zh-cn The Google Play publishing process is quite user-friendly - just follow the step-by-step instructions. First-time submission review may take longer, approximately 3 days in our case. Building Building aab format with Flutter is straightforward: run flutter build appbundle Created a script to dynamically pass build channels, e.g.: flutter build appbundle --dart-define=channel=google Due to initial unfamiliarity with aab format packaging causing runtime issues, added the following code to build.gradle: /// For handling channel parameters, set default values here def dartEnvironmentVariables = [ // Avoid using default values here to ensure always getting CLI args channel: \u0026#39;_channel\u0026#39;, ] if (project.hasProperty(\u0026#39;dart-defines\u0026#39;)) { dartEnvironmentVariables = dartEnvironmentVariables + project.property(\u0026#39;dart-defines\u0026#39;) .split(\u0026#39;,\u0026#39;) .collectEntries { entry -\u0026gt; def pair = new String(entry.decodeBase64(), \u0026#39;UTF-8\u0026#39;).split(\u0026#39;=\u0026#39;) [(pair.first()): pair.last()] } } android { if (dartEnvironmentVariables.channel == \u0026#34;google\u0026#34;) { // Use the bundle block to control configuration APK types bundle { language { // Disable language resource splits enableSplit = false } density { // Disabled by default enableSplit = false } abi { // Disabled by default enableSplit = false } } } } Screenshot 2.png ","date":"2022-04-15T14:41:25+08:00","image":"https://sethix.com/posts/2022041514/cover_hu2c0f3e8f03451ee00cd5e852d38c162a_32790_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022041514/","title":"YouMengji Launched on Google Play"},{"content":"Problem Analysis While reviewing legacy code, we discovered Redis operations without TTL settings. This likely occurred because:\nHash structures can\u0026rsquo;t set expiration time during creation Subsequent developers forgot to add expiration Common problematic patterns:\nDate-based Hash keys\nHSET xxx:ad_id:20220315 userid value Orphaned ad keys\nHSET xxx:ad_id userid value (after ad campaign ended) Initial cluster status: 8-node cluster with 8GB/node, but actual usage reached 51G+\nMemory overconsumption forced continuous resource scaling\nRedis Cluster Memory Usage Optimization Strategies 1. Key Distribution Analysis Used Alibaba Cloud\u0026rsquo;s offline analysis platform:\nhttps://help.aliyun.com/document_detail/102093.htm Alternative method (using redis-cli):\nredis-cli --bigkeys -i 0.1 (remove -i during off-peak) Alibaba Cloud Analysis 2. Code Refactoring Added TTL for date-based keys:\nEXPIRE xxx:ad_id:20220315 86400 Implemented cleanup for expired ads:\nUNLINK xxx:ad_id 3. Legacy Data Cleanup Modern Redis (≥4.0) solution:\nUNLINK xxx:ad_id:20220315 Bulk deletion pattern:\nredis-cli --scan --pattern xxx:ad_id:* | xargs redis-cli unlink 4. Memory Fragmentation Management After massive deletions, monitor fragmentation ratio:\nmem_fragmentation_ratio = used_memory_rss / used_memory Memory Fragmentation Recommended configuration for auto-defrag: activedefrag yes active-defrag-ignore-bytes 100mb active-defrag-threshold-lower 10 active-defrag-threshold-upper 100 active-defrag-cycle-min 25 active-defrag-cycle-max 75 Fragmentation reduction progress after 12 hours: Defrag Progress Important Notes 1. Data Backup Protocol Check last backup timestamp:\nLASTSAVE Initiate backup:\nBGSAVE Verify completion:\nCompare timestamps via LASTSAVE 2. Redis Expiration Mechanism Redis expires keys in two ways: passive and active.\nPassive expiration occurs when clients access keys and find them expired.\nActive expiration runs 10 times/second:\nRandomly test 20 keys from expiration set Delete expired keys If \u0026gt;25% keys expired, repeat step 1 Warning: The default File cache driver in Laravel uses passive expiration. Combined with ThrottleRequests middleware, this can cause massive file accumulation. ","date":"2022-03-16T10:09:52+08:00","image":"https://sethix.com/posts/2022031610/cover_hu602cca1c136d4c8968c0a94701d55eaa_13425_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022031610/","title":"Optimizing Redis Memory Usage for Ad Service: Reducing 30G+ Memory Footprint"},{"content":"Connecting a buzzer is relatively simple. You\u0026rsquo;ll need a buzzer module (I\u0026rsquo;m using an active/passive buzzer module).\nBuzzer The buzzer has only three pins. Here\u0026rsquo;s the wiring reference:\nRaspberry Pi Buzzer Note VUSB VCC 5V power (Pin 40) GP22 I/O GPIO pin GND GND Ground Found an arrangement of \u0026ldquo;Iron Blood Loyal Heart\u0026rdquo; online:\npackage main import ( \u0026#34;machine\u0026#34; \u0026#34;time\u0026#34; \u0026#34;tinygo.org/x/drivers/buzzer\u0026#34; ) type note struct { tone float64 duration float64 } func main() { // Note that 22 here is the I/O pin bzrPin := machine.Pin(22) bzrPin.Configure(machine.PinConfig{Mode: machine.PinOutput}) bzr := buzzer.New(bzrPin) song := []note{ {buzzer.A4, 1.5}, // 6 {buzzer.G4, 0.5}, // 5 // ... (Full musical notes arrangement) {buzzer.A3, 3.0}, // .6 } for _, val := range song { bzr.Tone(val.tone, val.duration) time.Sleep(10 * time.Millisecond) } } Compile and flash:\ngo mod tidy tinygo flash -target=pico Now enjoy the music!\n","date":"2022-03-15T22:19:56+08:00","image":"https://sethix.com/posts/2022031522/cover_hu8c7e27bb35dce06ad1a0e1cfeae5c728_30230_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022031522/","title":"[IoT] Raspberry Pi Pico Plays Music via Buzzer"},{"content":" A craftsman must sharpen his tools to do his work well. First, let\u0026rsquo;s configure our development environment. Refer to the official TinyGo IDE integration guide: https://tinygo.org/docs/guides/ide-integration/ Using GoLand 2021 as our IDE, follow these steps: Install the TinyGo plugin: JetBrains Plugin Repository or search directly in File -\u0026gt; Settings -\u0026gt; Plugins After installation, configure the board type at File -\u0026gt; Settings -\u0026gt; Go -\u0026gt; TinyGo (select \u0026ldquo;pico\u0026rdquo; in this case) Restart GoLand 2021 to activate Pico-specific code completion TinyGo Plugin The display used in this project is a 0.96-inch OLED 128x32 module: 0.96-inch OLED Display Wiring configuration based on Pico\u0026rsquo;s default I2C pins:\nRaspberry Pi Display Note 3V3 VCC Power supply GND GND Ground GP5 SCL Clock line GP4 SDA Data line After connecting the wires, verify the display resolution (128x32 in this case). Initialize the project: mkdir display_demo \u0026amp;\u0026amp; cd display_demo go mod init display_demo Create main.go with the following code (adapted from TinyGo Drivers Example): package main import ( \u0026#34;machine\u0026#34; \u0026#34;image/color\u0026#34; \u0026#34;time\u0026#34; \u0026#34;tinygo.org/x/drivers/ssd1306\u0026#34; ) func main() { machine.I2C0.Configure(machine.I2CConfig{ Frequency: machine.TWI_FREQ_400KHZ, SDA: machine.I2C0_SDA_PIN, SCL: machine.I2C0_SCL_PIN, }) display := ssd1306.NewI2C(machine.I2C0) display.Configure(ssd1306.Config{ Address: ssd1306.Address_128_32, Width: 128, Height: 32, }) display.ClearDisplay() x, y := int16(0), int16(0) deltaX, deltaY := int16(1), int16(1) for { pixel := display.GetPixel(x, y) c := color.RGBA{255, 255, 255, 255} if pixel { c = color.RGBA{0, 0, 0, 255} } display.SetPixel(x, y, c) display.Display() x += deltaX y += deltaY if x == 0 || x == 127 { deltaX = -deltaX } if y == 0 || y == 31 { deltaY = -deltaY } time.Sleep(1 * time.Millisecond) } } Flash the code to Pico: go mod tidy tinygo flash -target=pico Successful execution will show an animation: Displaying Text Using font generation tools (configuration shown below): Font Generation Tool Modified main.go for text display:\npackage main import ( \u0026#34;image/color\u0026#34; \u0026#34;machine\u0026#34; \u0026#34;time\u0026#34; \u0026#34;tinygo.org/x/drivers\u0026#34; \u0026#34;tinygo.org/x/drivers/ssd1306\u0026#34; ) // [...] (Keep the same display initialization code) var wordData = [][][]byte{ // Chinese character data arrays // (Maintain original byte arrays here) } var Key = [8]byte{0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01} func displayText(display drivers.Displayer, x, y int, wordData [][]byte) { // Pixel drawing implementation // (Maintain original pixel manipulation logic) } Flash the updated code: go mod tidy tinygo flash -target=pico Final result showing text animation: ","date":"2022-03-12T10:10:38+08:00","image":"https://sethix.com/posts/2022031210/cover_huf81c1b47938dc1cd2a121eaf50d410a8_42995_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2022031210/","title":"[IoT] Raspberry Pi Pico Lighting Up the Display"},{"content":"Introduction As a complete novice in IoT development, after several days of online research, I learned that:\nESP32https://www.espressif.com/zh-hans/products/socs/esp32 is the king of cost-performance (built-in WiFi + Bluetooth) Raspberry Pi Pico is beginner-friendly and easy to blink LEDs To balance both cost-performance and ease of use, I bought both boards Both have official Taobao stores linked from their official websites: Raspberry Pi Espressif Systems Both boards cost around 20-30 RMB Windows Environment Variables Right-click Computer (or open any folder and right-click \u0026ldquo;This PC\u0026rdquo;) -\u0026gt; Properties -\u0026gt; Advanced System Settings -\u0026gt; Environment Variables -\u0026gt; Double-click PATH (System variables) -\u0026gt; Add new paths as needed Go Installation Download from https://golang.google.cn/dl/ Select the appropriate version, e.g., Windows 64-bit: https://golang.google.cn/dl/go1.17.8.windows-amd64.zip Add C:\\go\\bin to system PATH after extraction Verify in new CMD: go version go version go1.17.8 windows/amd64 TinyGo Setup Follow official installation guide Download Windows 64-bit version: https://github.com/tinygo-org/tinygo/releases/download/v0.22.0/tinygo0.22.0.windows-amd64.zip Add c:\\tinygo\\bin to system PATH after extraction Verify in new CMD: tinygo version tinygo version 0.22.0 windows/amd64 (using go version go1.17.5 and LLVM version 13.0.0) Raspberry Pi Pico Recommended to get an expansion board for easier pin access Pre-soldered headers save time - simply plug the dev board into the expansion board Raspberry Pi Pico First project: LED blinking. Pico is remarkably simple compared to ESP32 - no extra toolchain needed\nDirectly connect to PC via USB and flash code\nTo enter bootloader mode:\nHold BOOTSEL button Connect USB cable Release BOOTSEL Flash new code ESP32 Setup Prerequisites Requires make command - use MSYS2 on Windows Official setup guide: https://docs.espressif.com/projects/esp-idf/en/release-v3.0/get-started/windows-setup.html ESP32 Dev Board Installation Steps Install MINGW32 (recommend C:\\msys32) Download: https://dl.espressif.com/dl/esp32_win32_msys2_environment_and_toolchain-20180110.zip Run C:\\msys32\\mingw32.exe for MINGW32 terminal Get ESP-IDF mkdir -p ~/esp \u0026amp;\u0026amp; cd ~/esp git clone -b release/v3.0 --recursive https://github.com/espressif/esp-idf.git Set IDF_PATH echo \u0026#34;export IDF_PATH=\\\u0026#34;C:/msys32/home/your-username/esp/esp-idf\\\u0026#34;\u0026#34; \u0026gt; /etc/profile.d/export_idf_path.sh Restart MINGW32 and verify: printenv IDF_PATH Create Project cd ~/esp cp -r $IDF_PATH/examples/get-started/hello_world . cd hello_world make menuconfig Configure serial port under Serial flasher config -\u0026gt; Default serial port ESP-IDF Config Serial Config Find COM port in Windows Device Manager Device Manager Set correct COM port (e.g., COM3) and save COM Port Setting Flash Firmware make flash Install esptool pip install esptool Will update Raspberry Pi Pico section next time. Stay tuned!\nCommon Errors Error 1 Makefile:8: C:/msys32/home/user-name/esp/esp-idf/make/project.mk: No such file or directory make: *** No rule to make target \u0026#39;C:/msys32/home/user-name/esp/esp-idf/make/project.m\u0026#39;. Stop. Fix: Verify IDF_PATH in /etc/profile.d/export_idf_path.sh uses correct username Error 2 make flash: could not open port \u0026#39;/dev/ttyUSB0 Fix: Ensure correct COM port is set in make menuconfig configuration ","date":"2022-03-09T17:59:04+08:00","image":"https://sethix.com/posts/2022030917/cover_hu239cd97c2920ec3fe76281922c9d138c_64038_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022030917/","title":"[IoT] Getting Started - Blinking the LED"},{"content":"Environment Configuration FROM phpswoole/swoole:php7.4-alpine # A script for installing PHP extensions COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/ RUN install-php-extensions pcntl redis pdo_mysql WORKDIR /var/www COPY . . RUN chmod -R 0777 storage \u0026amp;\u0026amp; \\ chmod -R 0777 bootstrap/cache \u0026amp;\u0026amp; \\ composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ \u0026amp;\u0026amp; \\ composer install --optimize-autoloader --no-dev \u0026amp;\u0026amp; \\ php artisan config:cache \u0026amp;\u0026amp; \\ php artisan route:cache \u0026amp;\u0026amp; \\ php artisan view:cache \u0026amp;\u0026amp; \\ php artisan laravels publish --no-interaction CMD [\u0026#34;php\u0026#34;, \u0026#34;bin/laravels\u0026#34;, \u0026#34;start\u0026#34;, \u0026#34;--env=product\u0026#34;] Deployment ## Build the image docker build . -t demo-image ## Run container docker run -d -p 80:5200 --name=demo-service demo-image Development Mount local directory for development ## Run container (/mnt/d/laravels-demo should be your project path) docker run -d -it -p 80:5200 -v /mnt/d/laravels-demo:/var/dev --name=demo-service -w /var/dev demo-image /bin/sh Auto-reload on code changes ## Enter container docker exec -it demo-service /bin/sh # Install inotify install-php-extensions inotify ## Modify .env LARAVELS_INOTIFY_RELOAD=true ## Start with auto-reload php bin/laravels start Model annotations and code navigation ## Enter container docker exec -it demo-service /bin/sh ## Install dependency composer install barryvdh/laravel-ide-helper ## Generate model annotations php artisan ide-helper:models --dir=\u0026#34;app/Models\u0026#34; --write --reset Debugging Using dump ## Enter container docker exec -it demo-service /bin/sh ## Install dependency composer install beyondcode/laravel-dump-server ## Capture dump outputs php artisan dump-server Using Swoole Tracker 3.1 Installation guide: https://wenda.swoole.com/detail/107688 Place .so file in container and enable extension in php.ini Add trackerHookMalloc function and run: php -r \u0026quot;trackerAnalyzeLeak();\u0026quot; Queue (Using Supervisor) Configuration Create queue.Dockerfile: FROM phpswoole/swoole:php7.4-alpine RUN sed -i \u0026#39;s/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g\u0026#39; /etc/apk/repositories \u0026amp;\u0026amp; cat /etc/apk/repositories COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/ RUN install-php-extensions pcntl redis pdo_mysql zip WORKDIR /var/www COPY . . RUN chmod -R 0777 storage \u0026amp;\u0026amp; \\ chmod -R 0777 bootstrap/cache \u0026amp;\u0026amp; \\ composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ \u0026amp;\u0026amp; \\ composer install --optimize-autoloader --no-dev ## Install Supervisor RUN apk add supervisor ## Supervisor configuration RUN mkdir /etc/supervisor.d/ \u0026amp;\u0026amp; echo $\u0026#39;\\n\\ [program:laravel-worker] \\n\\ process_name=%(program_name)s_%(process_num)02d \\n\\ command=/usr/local/bin/php /var/www/artisan queue:work --sleep=3 --tries=3 \\n\\ numprocs=12 \\n\\ autostart=true \\n\\ autorestart=true \\n\\ redirect_stderr=true \\n\\ stdout_logfile_maxbytes=10MB \\n\\ stdout_logfile=/var/www/storage/logs/queue.log \\n\u0026#39;\\ \u0026gt; /etc/supervisor.d/laravel-worker.ini CMD [\u0026#34;/usr/bin/supervisord\u0026#34;, \u0026#34;--nodaemon\u0026#34;, \u0026#34;-c\u0026#34;, \u0026#34;/etc/supervisord.conf\u0026#34;] Build queue image: docker build . -f queue.Dockerfile -t laravel-worker Run container: docker run -d --name=laravel-worker-service laravel-worker Queue Management Graceful restart: php artisan queue:restart Code update methods: Copy code to container and restart queue Use volume mapping Rebuild container image Tips New queue jobs don\u0026rsquo;t require restart Important Notes Set listen_ip to 0.0.0.0 in config/laravels.php Enable handle_static for static assets Check register_providers and cleaners configurations Maintain proper file permissions for storage and cache directories ","date":"2022-03-01T18:12:32+08:00","image":"https://sethix.com/posts/2022030118/cover_huc7a1e9c91aac973a3010371252a6d86c_24917_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022030118/","title":"Using laravel-s in Docker (Including Queue Usage)"},{"content":"Preface There are many installation tutorials online. Due to updates in gRPC, many commands may become obsolete. This article reflects the current state at the time of writing. If you encounter issues, the best approach is to refer to the official documentation Installation First install Go Install the protoc compiler https://grpc.io/docs/protoc-installation/ The protoc compiler is used to compile .proto files containing service and message definitions Download the zip file matching your OS and architecture (e.g., protoc-3.19.4-linux-x86_64.zip for WSL) https://github.com/protocolbuffers/protobuf/releases Extract the downloaded package: unzip protoc-3.19.4-linux-x86_64.zip -d $HOME/.local Add to PATH: vim ~/.bashrc and add: export PATH=\u0026quot;$PATH:$HOME/.local/bin\u0026quot; source ~/.bashrc to refresh environment variables Verify with protoc --version Install Go plugins The protoc compiler requires these plugins to generate Go code: go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.26 gRPC code generator plugin (previously included in protoc-gen-go): go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.1 Core Concepts gRPC supports four service method types: Unary RPC: Client sends single request, server returns single response (like normal function call) Server streaming: Client sends request, gets stream to read message sequence Client streaming: Client sends stream of messages, server returns single response Bidirectional streaming: Both sides send message streams independently Use repeated for bounded datasets that can be generated quickly, stream for large/potentially unbounded datasets Example Implementation Project Setup mkdir grpc-demo \u0026amp;\u0026amp; cd grpc-demo go mod init github.com/seth-shi/grpc-demo Protocol Definitions pb/goods.proto:\nsyntax = \u0026#34;proto3\u0026#34;; package pb; option go_package=\u0026#34;github.com/seth-shi/grpc-demo/pb\u0026#34;; service Goods { rpc Show(GoodsShowRequest) returns (GoodsData); } message GoodsShowRequest { int64 id = 1; } message GoodsData { int64 id = 1; string name = 2; double amount = 3; } pb/order.proto:\nsyntax = \u0026#34;proto3\u0026#34;; package pb; option go_package=\u0026#34;github.com/seth-shi/grpc-demo/pb\u0026#34;; service Order { rpc Index(OrderIndexRequest) returns (OrderIndexResponse); rpc Store(OrderStoreRequest) returns (OrderData); } message OrderIndexRequest { int64 userId = 1; } message OrderIndexResponse { repeated OrderData data = 1; } message OrderStoreRequest { int64 goodsId = 1; int64 goodsNumber = 2; int64 userId = 3; double Amount = 4; string goodsName = 5; } message OrderData { int64 no = 1; double amount = 2; int64 number = 3; int64 goodsId = 4; string goodsName = 5; } Generate Go code:\nprotoc --go_out=. --go_opt=paths=source_relative \\ --go-grpc_out=. --go-grpc_opt=paths=source_relative \\ pb/*.proto go mod tidy Service Implementations goods/main.go:\npackage main // ... goods service implementation ... order/main.go:\npackage main // ... order service implementation ... API Gateway api/main.go:\npackage main // ... API implementation with Gin ... Running the System # Start services in separate terminals go run goods/main.go go run order/main.go go run api/main.go Common Errors rpc error: code = Unavailable desc = connection error: Common in WSL environments - try running services directly on host machine Ensure ports are not blocked by firewall Verify service addresses match in client connections This implementation demonstrates basic gRPC patterns including:\nProtocol definition with Protobuf Service implementation patterns Client-server communication Error handling basics API gateway pattern ","date":"2022-02-25T18:29:43+08:00","image":"https://sethix.com/posts/2022022518/cover_hubd506480d4917e37a3c530ae532ccd0f_18609_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022022518/","title":"Using gRPC"},{"content":"Installation Many online tutorials simply use a single Docker command:\ndocker run -it -p 4040:4040 --restart=always pyroscope/pyroscope:latest server However, this basic installation lacks crucial configurations: no authentication for the data dashboard, no API reporting restrictions (e.g., limiting reporting via API keys), and no data persistence after container destruction. Here\u0026rsquo;s a better approach using docker-compose.yml: version: \u0026#34;3\u0026#34; services: pyroscope: image: \u0026#34;pyroscope/pyroscope:latest\u0026#34; ports: - \u0026#34;4040:4040\u0026#34; command: - \u0026#34;server\u0026#34; environment: ## Enforce API key authentication for data ingestion - PYROSCOPE_AUTH_INGESTION_ENABLED=true ## Enable login for web dashboard - PYROSCOPE_AUTH_INTERNAL_ENABLED=true volumes: ## Persistent data storage - ./data:/var/lib/pyroscope After configuration, run docker-compose up -d and access 127.0.0.1:4040 to see the login page. Default credentials: admin/admin (change after initial login). Add API keys under Settings -\u0026gt; API Keys -\u0026gt; Add Key. Note: Select Agent role for data reporting permissions. Pyroscope Go Implementation Go supports two modes: pull mode (like Prometheus) and push mode. For personal projects, push mode is recommended.\nAdd dependency: # Ensure pyroscope server version ≥0.3.1 go get github.com/pyroscope-io/client/pyroscope Initialize in code: package main import \u0026#34;github.com/pyroscope-io/client/pyroscope\u0026#34; func main() { pyroscope.Start(pyroscope.Config{ // Application name (must be in English, no Chinese characters) ApplicationName: \u0026#34;remeber-dream-api\u0026#34;, ServerAddress: \u0026#34;127.0.0.1:4040\u0026#34;, Logger: pyroscope.StandardLogger, // Required if PYROSCOPE_AUTH_INGESTION_ENABLED is enabled AuthToken: \u0026#34;xxxx\u0026#34;, // Select profiling types (default: all enabled) ProfileTypes: []pyroscope.ProfileType{ pyroscope.ProfileCPU, pyroscope.ProfileAllocObjects, pyroscope.ProfileAllocSpace, pyroscope.ProfileInuseObjects, pyroscope.ProfileInuseSpace, }, }) // Your application logic } PHP Implementation Native PHP profiling (via official docs) works best for CLI. For PHP-FPM, enable slow logs instead.\nFor Swoole-based projects like laravel-s:\nDockerfile example:\nFROM phpswoole/swoole:php7.4 # Change to Chinese mirror source RUN sed -i \u0026#34;s@http://deb.debian.org@http://mirrors.aliyun.com@g\u0026#34; /etc/apt/sources.list \u0026amp;\u0026amp; rm -rf /var/lib/apt/lists/* \u0026amp;\u0026amp; apt-get update # Install PHP extensions COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/ RUN install-php-extensions pcntl redis pdo_mysql gd WORKDIR /var/www COPY . . RUN chmod -R 0777 storage \u0026amp;\u0026amp; \\ chmod -R 0777 bootstrap/cache \u0026amp;\u0026amp; \\ composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ \u0026amp;\u0026amp; \\ composer install --optimize-autoloader --no-dev \u0026amp;\u0026amp; \\ php artisan config:cache \u0026amp;\u0026amp; \\ php artisan route:cache \u0026amp;\u0026amp; \\ php artisan view:cache \u0026amp;\u0026amp; \\ php artisan laravels publish --no-interaction # Copy pyroscope binary from official image COPY --from=pyroscope/pyroscope:latest /usr/bin/pyroscope /usr/bin/pyroscope ## Recommended to inject credentials via runtime environment #ENV PYROSCOPE_SERVER_ADDRESS= #ENV PYROSCOPE_APPLICATION_NAME= #ENV PYROSCOPE_AUTH_TOKEN= CMD [\u0026#34;pyroscope\u0026#34;, \u0026#34;exec\u0026#34;, \u0026#34;php\u0026#34;, \u0026#34;bin/laravels\u0026#34;, \u0026#34;start\u0026#34;, \u0026#34;--env=production\u0026#34;] Key Notes Avoid Alpine-based images (compatibility issues). Inject credentials via docker run --env instead of hardcoding in Dockerfile. Use pyroscope exec before your main command as shown in docs. Final result: Pyroscope For a cached API endpoint under load testing, most time is spent on route matching and Redis operations. Metric Explanations Metric Description cpu CPU usage inuse_objects Allocated but unreleased objects alloc_objects Total allocated objects (including released) inuse_space Allocated but unreleased memory alloc_space Total allocated memory (including freed) ","date":"2022-02-15T16:23:40+08:00","image":"https://sethix.com/posts/2022021516/cover_hu27bcf17faacece54ceec1e468d34426f_14346_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022021516/","title":"Advanced Usage of Pyroscope for Go and PHP Performance Analysis"},{"content":"Environment Setup Built using swoole:alpine Docker image FROM phpswoole/swoole:php7.4-alpine RUN sed -i \u0026#39;s/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g\u0026#39; /etc/apk/repositories \u0026amp;\u0026amp; cat /etc/apk/repositories # Quick PHP extension installation COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/ RUN install-php-extensions pcntl redis pdo_mysql WORKDIR /var/www COPY . . RUN chmod -R 0777 storage \u0026amp;\u0026amp; \\ chmod -R 0777 bootstrap/cache \u0026amp;\u0026amp; \\ composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ \u0026amp;\u0026amp; \\ composer install --optimize-autoloader --no-dev \u0026amp;\u0026amp; \\ php artisan config:cache \u0026amp;\u0026amp; \\ php artisan route:cache \u0026amp;\u0026amp; \\ php artisan view:cache \u0026amp;\u0026amp; \\ php artisan laravels publish --no-interaction CMD [\u0026#34;php\u0026#34;, \u0026#34;bin/laravels\u0026#34;, \u0026#34;start\u0026#34;, \u0026#34;--env=product\u0026#34;] For initial setup, comment out the last two lines in Dockerfile: docker build . -t test-image docker run -d -it -p 80:5200 -v [/mnt/d/xxxx]:/var/dev --name=test-service -w /var/dev test-image /bin/sh docker exec -it memory-service /bin/sh Error Logs [2022-01-01 02:29:45 $19.0]\tWARNING\tServer::check_worker_exit_status(): worker(pid=1641, id=5) abnormal exit, status=255, signal=0 [2022-01-01 02:30:24 *1642.0]\tERROR\tphp_swoole_server_rshutdown() (ERRNO 503): Fatal error: Allowed memory size of 134217728 bytes exhausted... ... (truncated for brevity) Official Documentation Guidance Set up cleaners Known Issues Memory Leak Prevention Avoid global variables or manually clean them Prevent infinite appends to static variables/singletons // Bad practice example class Test { public static $array = []; public static $string = \u0026#39;\u0026#39;; } Memory Leak Detection Modify config/laravels.php: \u0026#39;worker_num\u0026#39; =\u0026gt; 1, \u0026#39;max_request\u0026#39; =\u0026gt; 1000000, Add debug route: Route::get(\u0026#39;/debug-memory-leak\u0026#39;, function () { global $previous; $current = memory_get_usage(); $stats = [ \u0026#39;prev_mem\u0026#39; =\u0026gt; $previous, \u0026#39;curr_mem\u0026#39; =\u0026gt; $current, \u0026#39;diff_mem\u0026#39; =\u0026gt; $current - $previous, ]; $previous = $current; return $stats; }); Monitor memory changes using: watch -n 1 curl 127.0.0.1:5200/debug-memory-leak Using Swoole Tracker 3.1 Install free version following official guide Add tracker hooks: trackerHookMalloc(); Analyze leaks: php -r \u0026#34;trackerAnalyzeLeak();\u0026#34; Sample Leak Report [29260 (Loop 4252)] /var/dev/vendor/facade/ignition/src/QueryRecorder/QueryRecorder.php:44 =\u0026gt; [-192] ... (truncated) Root Cause Analysis The memory leak originated from repeated command registration in AdminServiceProvider:\npublic function register() { // Problematic code $this-\u0026gt;commands($this-\u0026gt;commands); if (config(\u0026#39;app.debug\u0026#39;)) { $this-\u0026gt;commands($this-\u0026gt;devCommands); } } Each request appended commands to Artisan::$bootstrappers, causing memory growth:\npublic static function starting(Closure $callback) { static::$bootstrappers[] = $callback; // Memory leak source } Solution Remove unnecessary service provider registration in laravels.register_providers Implement proper cleanup mechanisms Use max_request as safety net: \u0026#39;max_request\u0026#39; =\u0026gt; 500, // Handle 500 requests per worker Final Docker CMD:\nCMD [\u0026#34;php\u0026#34;, \u0026#34;bin/laravels\u0026#34;, \u0026#34;start\u0026#34;, \u0026#34;--env=product\u0026#34;] ","date":"2022-01-05T10:54:45+08:00","image":"https://sethix.com/posts/2022010510/cover_hud230a29bcdb3a9724df5190782b51a3e_61035_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2022010510/","title":"Troubleshooting Laravel-S Memory Leak with Swoole Tracker"},{"content":"Preface I\u0026rsquo;ve encountered sleep paralysis multiple times, struggling to wake up until I found that shaking my head vigorously can break the spell.\nLiu Cixin once said: \u0026ldquo;Imagination is an ability humans possess that seems like it should belong solely to gods. Its significance far exceeds our understanding.\u0026rdquo;\nIn dreams, your imagination becomes extraordinarily powerful.\nThe Dream It didn\u0026rsquo;t feel like a typical dream—I was fully conscious, even hearing voices outside the window clearly. I knew I was dreaming. I tried to sit up, but an invisible force pinned me down. The harder I struggled, the stronger the restraining force became. Then I remembered an old trick: shaking my head. A slight head movement almost woke me, yet part of me wanted to linger in the dream state where I had absolute control. Returning to the dream, I kept attempting to rise but failed repeatedly. Finally, a forceful head shake jolted me awake. I suspect this works because physical movement (unlike trying to sit up) disrupts brain activity—possibly shifting the pituitary gland\u0026rsquo;s position—interrupting the dream state.\nConclusion Research suggests this was a lucid dream. While some articles mention counting numbers as a wake-up method, I\u0026rsquo;m convinced that head movement triggers faster awakening. This might relate to physical repositioning affecting brain functions.\n","date":"2021-11-14T10:09:29+08:00","image":"https://sethix.com/posts/2021111410/cover_hu6410b296edc93472981f6e5f20e69f26_32577_120x120_fill_q75_box_smart1.jpg","permalink":"https://sethix.com/posts/2021111410/","title":"Can Shaking Your Head Wake You Up from a Dream?"},{"content":"Start Previously, I configured message push notifications on CODING for all successful project deployments. As the number of projects increased and other services required message notifications, the free quota provided by Server Chan became insufficient.\nAfter researching two commonly used services, both have frequency limitations:\nServer Chan: Free tier allows only 5 messages/day Qmsg Chan: 30 messages/day with occasional instability Configuration Discovered that Server Chan\u0026rsquo;s documentation teaches how to build a WeCom bot service. Repository: https://github.com/easychen/wecomchan Followed the README to register a WeCom enterprise account (individual users can create an \u0026ldquo;enterprise\u0026rdquo; with personal information) Obtained API parameters (agentid, secret, corpid) for sending messages through WeCom\u0026rsquo;s API Server Chan provides a pre-built Go service: https://github.com/easychen/wecomchan/blob/main/go-wecomchan/README.md Modified CODING deployment scripts to send requests to my self-hosted service instead of Server Chan: // Server Chan sshCommand( remote: remoteConfig, command: \u0026#34;curl -X POST -d \\\u0026#34;title=`echo \\$(curl -I 127.0.0.1:8199/ping)`\u0026amp;desp=Message details\\\u0026#34; https://sctapi.ftqq.com/xxxx.send\u0026#34;, sudo: true, ) // Modified version sshCommand( remote: remoteConfig, command: \u0026#34;curl -X POST -d \\\u0026#34;sendkey=xxxxxxx\u0026amp;msg_type=text\u0026amp;msg=${DOCKER_REPO_NAME}%0D%0A${SERVICE_URL}%0D%0A%0D%0A`echo \\$(curl -I 127.0.0.1:8199/ping)`\\\u0026#34; http://127.0.0.1:8080/wecomchan\u0026#34;, sudo: true, ) Demo WeCom WeCom ","date":"2021-10-30T13:57:42+08:00","image":"https://sethix.com/posts/2021103013/cover_hu2227807ee3fbeb5b3c5cd07483704c97_43632_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021103013/","title":"Building a Message Push Service Bot Using WeCom"},{"content":"Preface Recently containerized all Go programs on the server for deployment Combined with CODING\u0026rsquo;s CI/CD, deployment has become extremely pleasant But there were still several PHP projects remaining on the server Blog (Originally built with WordPress) Deploy Nginx and PHP containers, then reverse proxy via host machine Discovered Hugo (similar to Hexo), a static site generator Migrated blog to Hugo with fast builds and real-time previews Now runs in a single Nginx container with host reverse proxy Details: My Blog DreamNote Admin (Laravel) Original Nginx + PHP-FPM container approach Switched to persistent PHP runtime using laravel-s (supports dcat-admin) Official Swoole container docker-swoole with custom Dockerfile: FROM phpswoole/swoole:php7.4-alpine # PHP extension installer script COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/ RUN install-php-extensions pcntl redis pdo_mysql WORKDIR /var/www COPY . . RUN chmod -R 0777 storage \u0026amp;\u0026amp; \\ chmod -R 0777 bootstrap/cache \u0026amp;\u0026amp; \\ composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ \u0026amp;\u0026amp; \\ composer install --optimize-autoloader --no-dev \u0026amp;\u0026amp; \\ php artisan config:cache \u0026amp;\u0026amp; \\ php artisan route:cache \u0026amp;\u0026amp; \\ php artisan view:cache \u0026amp;\u0026amp; \\ php artisan laravels publish --no-interaction CMD [\u0026#34;php\u0026#34;, \u0026#34;bin/laravels\u0026#34;, \u0026#34;start\u0026#34;, \u0026#34;--env=product\u0026#34;] Key Configurations Provider Registration (config/laravels.php) \\Dcat\\Admin\\AdminServiceProvider::class, Cleaners Configuration Hhxsv5\\LaravelS\\Illuminate\\Cleaners\\SessionCleaner::class, Hhxsv5\\LaravelS\\Illuminate\\Cleaners\\AuthCleaner::class, Hhxsv5\\LaravelS\\Illuminate\\Cleaners\\DcatAdminCleaner::class, Essential Settings: \u0026#39;listen_ip\u0026#39; =\u0026gt; \u0026#39;0.0.0.0\u0026#39;, \u0026#39;handle_static\u0026#39; =\u0026gt; true // Enable for static assets Monday Mall (Laravel) Implemented same containerization approach Conclusion Successfully removed all native environments (Go/PHP/Python) from server Pure Docker environment now runs all services Easy migration and server replacement possible CODING CI/CD enables seamless container deployment Containerization achievement unlocked! 🐳🚀\n","date":"2021-10-24T16:05:45+08:00","image":"https://sethix.com/posts/2021102416/cover_hude649f97d827a9b65ff06c4b8c11b2f9_24857_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021102416/","title":"Containerizing All Services: Running PHP Code in Containers with Laravel-S"},{"content":"Now The blogging workflow is simple - after local writing, pushing code to CODING triggers full pipeline automation: Start local hugo server for writing Push to CODING for CI/CD (reference: Continuous Integration for Projects) Generate public directory using ubuntu image Package into nginx:alpine container (extremely lightweight) After build completion: Build plan deploys to server Container restarts Notification sent for successful deployment Step3 (2021-10-22) Switched to hugo (similar to hexo but written in Go instead of Node.js) Primary reason: Static blogs don\u0026rsquo;t natively support comment systems Step2 (2018-02-27) Reverted to WordPress Static sites struggled with comment integration Frequent GitHub access issues in China Step1 (2017) Established new blog using hexo + GitHub First experience with static site generators felt fresh and experimental Start (2016) First year of college, initial exposure to programming Purchased first cloud server on Tencent Cloud (1 yuan/month promo) Self-taught WordPress deployment through experimentation ","date":"2021-10-21T10:53:14+08:00","image":"https://sethix.com/posts/2021102110/cover_hu34d1daa649511483d914d8b19de6f65e_5409_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021102110/","title":"Blog Self-Description"},{"content":" https://coding.net/ provides 1000 minutes of free build resources per month\nRead the documentation first: https://help.coding.net/docs/ci/start.html Start Developed using https://github.com/gogf/gf. Modified its default Dockerfile (original requires host machine compilation for dependency caching; modified to perform all operations within the image). ############################################################################### # Use first-stage image for building ############################################################################### FROM golang as builder ENV GO111MODULE=on \\ GOPROXY=https://goproxy.cn,direct WORKDIR /app COPY . . RUN go mod tidy # Modified for CGO dependency: CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -ldflags \u0026#39;-extldflags \u0026#34;-static\u0026#34;\u0026#39; -o main main.go RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o main main.go ############################################################################### # Runtime image: Copy built files from builder ############################################################################### # FROM scratch FROM alpine # Use domestic alpine mirror RUN echo http://mirrors.aliyun.com/alpine/v3.8/main/ \u0026gt; /etc/apk/repositories # Set timezone to UTC+8 RUN apk update \u0026amp;\u0026amp; apk add tzdata ca-certificates bash RUN rm -rf /etc/localtime \u0026amp;\u0026amp; cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime RUN echo \u0026#34;Asia/Shanghai\u0026#34; \u0026gt; /etc/timezone ENV WORKDIR /var/www COPY --from=builder /app/main $WORKDIR/main COPY --from=builder /app/i18n $WORKDIR/i18n COPY --from=builder /app/public $WORKDIR/public COPY --from=builder /app/config $WORKDIR/config COPY --from=builder /app/template $WORKDIR/template COPY --from=builder /app/.env $WORKDIR/.env EXPOSE 9999 WORKDIR $WORKDIR CMD [\u0026#34;./main\u0026#34;] When creating a new build plan in CODING, select the CODING Docker Image Push template. Basic pipeline example: pipeline { agent any stages { stage(\u0026#39;Checkout\u0026#39;) { steps { checkout([$class: \u0026#39;GitSCM\u0026#39;, branches: [[name: GIT_BUILD_REF]], userRemoteConfigs: [[ url: GIT_REPO_URL, credentialsId: CREDENTIALS_ID ]]]) } } stage(\u0026#39;Set Environment Variables\u0026#39;) { steps { writeFile(file: \u0026#39;.env\u0026#39;, text: \u0026#39;DATABASE_DSN=mysql:root:12345678@tcp(127.0.0.1:3306)/test2\u0026#39;) } } stage(\u0026#39;Build \u0026amp; Push Image\u0026#39;) { steps { sh \u0026#34;docker build -t ${CODING_DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_VERSION} -f ${DOCKERFILE_PATH} ${DOCKER_BUILD_CONTEXT}\u0026#34; useCustomStepPlugin(key: \u0026#39;codingcorp:artifact_docker_push\u0026#39;, version: \u0026#39;latest\u0026#39;, params: [image:\u0026#34;${CODING_DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_VERSION}\u0026#34;,repo:\u0026#34;${DOCKER_REPO_NAME}\u0026#34;]) } } stage(\u0026#39;Deploy to Remote\u0026#39;) { steps { script { def remoteConfig = [:] remoteConfig.name = \u0026#34;my-remote-server\u0026#34; remoteConfig.host = \u0026#34;${REMOTE_HOST}\u0026#34; remoteConfig.port = \u0026#34;${REMOTE_SSH_PORT}\u0026#34;.toInteger() remoteConfig.allowAnyHosts = true withCredentials([ sshUserPrivateKey( credentialsId: \u0026#34;${REMOTE_CRED}\u0026#34;, keyFileVariable: \u0026#34;privateKeyFilePath\u0026#34; ), usernamePassword( credentialsId: \u0026#34;${CODING_ARTIFACTS_CREDENTIALS_ID}\u0026#34;, usernameVariable: \u0026#39;CODING_DOCKER_REG_USERNAME\u0026#39;, passwordVariable: \u0026#39;CODING_DOCKER_REG_PASSWORD\u0026#39; ) ]) { remoteConfig.user = \u0026#34;${REMOTE_USER_NAME}\u0026#34; remoteConfig.identityFile = privateKeyFilePath sshCommand( remote: remoteConfig, command: \u0026#34;docker login -u ${CODING_DOCKER_REG_USERNAME} -p ${CODING_DOCKER_REG_PASSWORD} ${CODING_DOCKER_REG_HOST}\u0026#34;, sudo: true, ) DOCKER_IMAGE_URL = sh( script: \u0026#34;echo ${CODING_DOCKER_REG_HOST}/${CODING_DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_VERSION}\u0026#34;, returnStdout: true ) sshCommand( remote: remoteConfig, command: \u0026#34;docker pull ${DOCKER_IMAGE_URL}\u0026#34;, sudo: true, ) sshCommand( remote: remoteConfig, command: \u0026#34;docker rm -f golang-coding | true\u0026#34;, sudo: true, ) sshCommand( remote: remoteConfig, command: \u0026#34;docker run --cpus=0.5 --memory=100m -d -p 8199:8199 --name golang-coding --restart=always ${DOCKER_IMAGE_URL}\u0026#34;, sudo: true, ) sshCommand( remote: remoteConfig, command: \u0026#34;docker image prune -a -f\u0026#34;, sudo: true, ) sshCommand( remote: remoteConfig, command: \u0026#34;curl -X POST -d \\\u0026#34;title=`echo \\$(curl -I 127.0.0.1:8199/ping)`\u0026amp;desp=Deploy success\\\u0026#34; https://sctapi.ftqq.com/xxxx.send\u0026#34;, sudo: true, ) echo \u0026#34;Deployed successfully. Preview at http://${REMOTE_HOST}:8199\u0026#34; } } } } } environment { CODING_DOCKER_REG_HOST = \u0026#34;${CCI_CURRENT_TEAM}-docker.pkg.${CCI_CURRENT_DOMAIN}\u0026#34; CODING_DOCKER_IMAGE_NAME = \u0026#34;${PROJECT_NAME.toLowerCase()}/${DOCKER_REPO_NAME}/${DOCKER_IMAGE_NAME}\u0026#34; } } Project Repository Reference implementation:\nhttps://github.com/seth-shi/golang-coding\n","date":"2021-10-14T16:59:36+08:00","image":"https://sethix.com/posts/2021101416/cover_hu05ea1304d7fd4cda52dfea61dc7716e8_7594_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021101416/","title":"Continuous Integration for Go Projects with CODING"},{"content":"Integrating Umeng is a huge pitfall for non-Android developers. Here\u0026rsquo;s my experience with some common pitfalls like UMConfigure not found, incorrect override syntax in Kotlin (official docs use Java), and misleading official plugins. The actual process is simple:\nStart with native integration first - even for Flutter apps. Follow Android integration steps before using any Flutter plugin. Official documentation: Umeng Android Integration Guide (replace if link expires) Always use maven automatic integration (repeat 3x) for non-native developers Native Setup in 3 Steps Dependency configuration\nAdd to project-level android/build.gradle: repositories { maven { url \u0026#39;https://repo1.maven.org/maven2/\u0026#39; } } Add to app-level android/app/build.gradle: dependencies { implementation \u0026#39;com.umeng.umsdk:common:9.4.4\u0026#39; implementation \u0026#39;com.umeng.umsdk:asms:1.4.1\u0026#39; } Permissions in android/app/src/main/AndroidManifest.xml:\n\u0026lt;manifest\u0026gt; \u0026lt;uses-permission android:name=\u0026#34;android.permission.ACCESS_NETWORK_STATE\u0026#34;/\u0026gt; \u0026lt;uses-permission android:name=\u0026#34;android.permission.ACCESS_WIFI_STATE\u0026#34;/\u0026gt; \u0026lt;uses-permission android:name=\u0026#34;android.permission.READ_PHONE_STATE\u0026#34;/\u0026gt; \u0026lt;application\u0026gt; \u0026lt;meta-data android:name=\u0026#34;UMENG_APPKEY\u0026#34; android:value=\u0026#34;YOUR_APP_KEY\u0026#34;/\u0026gt; \u0026lt;/application\u0026gt; \u0026lt;/manifest\u0026gt; ProGuard rules in android/app/proguard-rules.pro:\n-keep class com.umeng.** {*;} -keepclassmembers class * { public \u0026lt;init\u0026gt;(org.json.JSONObject); } Native Initialization In android/app/src/main/kotlin/com/xxxxx/MainActivity.kt:\nimport com.umeng.analytics.MobclickAgent import com.umeng.commonsdk.UMConfigure override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) UMConfigure.preInit(this, \u0026#34;your_app_key\u0026#34;, \u0026#34;Umeng\u0026#34;) } Flutter Initialization Add dependency in pubspec.yaml:\ndependencies: umeng_common_sdk: ^1.2.0 Initialize in Dart:\nimport \u0026#39;package:umeng_common_sdk/umeng_common_sdk.dart\u0026#39;; void main() { UmengCommonSdk.initCommon(\u0026#39;android_app_key\u0026#39;, \u0026#39;ios_app_key\u0026#39;, \u0026#39;Umeng\u0026#39;); runApp(MyApp()); } Verify data transmission in Umeng Dashboard\nNote: Keep monitoring real-time analytics in Umeng backend to confirm successful integration.\n","date":"2021-09-18T00:29:53+08:00","image":"https://sethix.com/posts/2021091800/cover_hu1b3bd691b356ac7313e819a1c1d8b6c5_27746_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021091800/","title":"Flutter Integration with Umeng: A Step-by-Step Record"},{"content":" While I\u0026rsquo;ve read many related articles before, true understanding comes from practice. Recently, the data team restructured logging formats. I designed a table schema and asked them to write cleaned client logs into it. As this is a video playback statistics table, we implemented date-based partitioning. With less than 100k videos in the library, we opted for monthly partitioning instead of daily. For auto-increment primary key id, you must create composite primary key with partitioning key In our actual implementation, we simply omitted the primary key `id` BIGINT UNSIGNED NOT NULL auto_increment, PRIMARY KEY(`id`, `date_key`) Partition by month Other playback statistics fields are omitted Records before 2021-09-01 will be stored in p_202108 partition Records from 2021-09-01 to 2021-09-30 will go to p_202109 partition CREATE TABLE `video_play_logs` ( `video_id` INT UNSIGNED NOT NULL, `date_key` date NOT NULL, index `video_play_logs_video_id_index` ( `video_id` ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci PARTITION BY RANGE(to_days(`date_key`)) ( PARTITION p_202108 VALUES LESS THAN (to_days(\u0026#39;20210901\u0026#39;)), PARTITION p_202109 VALUES LESS THAN (to_days(\u0026#39;20211001\u0026#39;)), PARTITION p_202110 VALUES LESS THAN (to_days(\u0026#39;20211101\u0026#39;)), PARTITION p_202111 VALUES LESS THAN (to_days(\u0026#39;20211201\u0026#39;)), PARTITION p_202112 VALUES LESS THAN (to_days(\u0026#39;20220101\u0026#39;)) ) Verify partition configuration Insert test data and check TABLE_ROWS for record counts in each partition SELECT TABLE_NAME, PARTITION_NAME, TABLE_ROWS FROM information_schema.`PARTITIONS` WHERE table_name=\u0026#39;video_play_logs\u0026#39; ORDER BY TABLE_ROWS desc +-----------------+----------------+------------+ | TABLE_NAME | PARTITION_NAME | TABLE_ROWS | +-----------------+----------------+------------+ | video_play_logs | p_202108 | 0 | | video_play_logs | p_202109 | 0 | | video_play_logs | p_202110 | 0 | | video_play_logs | p_202111 | 0 | | video_play_logs | p_202112 | 0 | | video_play_logs | p_202201 | 0 | | video_play_logs | p_202202 | 0 | | video_play_logs | p_202203 | 0 | | video_play_logs | p_202204 | 0 | ...... Check partition hit status When partitions column shows data, it indicates successful partition pruning EXPLAIN PARTITIONS SELECT * FROM video_play_logs where date_key=\u0026#39;2021-08-27\u0026#39;; +----+-------------+-----------------+------------+------+---------------+------+---------+------+------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-----------------+------------+------+---------------+------+---------+------+------+----------+-------------+ | 1 | SIMPLE | video_play_logs | p_202109 | ALL | NULL | NULL | NULL | NULL | 1 | 100.00 | Using where | +----+-------------+-----------------+------------+------+---------------+------+---------+------+------+----------+-------------+ 1 row in set (0.16 sec) ","date":"2021-08-27T15:46:03+08:00","image":"https://sethix.com/posts/2021082715/cover_hu6baf0dab89c4ad0bb46e1826794363cc_9559_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021082715/","title":"MySQL Partitioning Practice"},{"content":"According to the official documentation:\nDefault Directory Configuration\nWhen initializing the gcfg configuration management object, it automatically adds the following configuration file search directories by default:\nCurrent working directory and its config subdirectory: e.g., /home/www and /home/www/config when working in /home/www Executable file directory and its config subdirectory: e.g., /tmp and /tmp/config for a binary in /tmp Main package directory and its config subdirectory (only effective in source development): e.g., /home/john/workspace/gf-app and /home/john/workspace/gf-app/config for a main package in that directory During development, the configuration file can always be found correctly through the main package location regardless of binary relocation. Let\u0026rsquo;s examine the implementation in the GoFrame source code.\nLooking at the gcfg.New method:\nfunc New(file ...string) *Config { // ... [initialization logic] // Customized dir path from env/cmd handling if customPath := gcmd.GetOptWithEnv(commandEnvKeyForPath).String(); customPath != \u0026#34;\u0026#34; { // ... [custom path logic] } else { // Default directory processing // 1. Working directory if err := c.AddPath(gfile.Pwd()); err != nil { intlog.Error(context.TODO(), err) } // 2. Main package directory (development environment) if mainPath := gfile.MainPkgPath(); mainPath != \u0026#34;\u0026#34; { if err := c.AddPath(mainPath); err != nil { intlog.Error(context.TODO(), err) } } // 3. Executable directory if selfPath := gfile.SelfDir(); selfPath != \u0026#34;\u0026#34; { if err := c.AddPath(selfPath); err != nil { intlog.Error(context.TODO(), err) } } } return c } The key method gfile.MainPkgPath() works as follows:\nfunc MainPkgPath() string { // ... [initial checks] // Iterate through call stack for i := 1; i \u0026lt; 10000; i++ { pc, file, _, ok := runtime.Caller(i) if !ok { break } // Filter Go standard library paths if isStandardLibraryFile(file) { continue } // Check if it\u0026#39;s a main package file if strings.Contains(getFileContent(file), \u0026#34;package main\u0026#34;) { return filepath.Dir(file) } } // Fallback directory search // ... [directory traversal logic] } Key implementation points:\nCall Stack Traversal: Uses runtime.Caller to traverse up to 10,000 call frames Main Package Identification: Checks files for package main declaration Path Validation: Verifies path existence and proper directory structure How runtime.Caller Works Internally The Go runtime maintains execution context through:\n// Simplified runtime.Caller implementation func Caller(skip int) (pc uintptr, file string, line int, ok bool) { rpc := make([]uintptr, 1) n := callers(skip+1, rpc[:]) // Adjust for wrapper frames frame, _ := CallersFrames(rpc).Next() return frame.PC, frame.File, frame.Line, true } Key components:\nProgram Counter (PC): Unique identifier for execution position Symbol Table: Built during linking (go build phase) Module Data: Stores debug information and source mapping Go Linker Write Timing Diagram Compilation and Linking Process (Image from Go Compilation Overview)\nPractical Implications Development vs Production\nDevelopment: Reliable main package detection through source analysis Production: Falls back to executable directory detection Performance Considerations\nCall stack traversal has O(n) complexity but optimized for typical cases Path caching (mainPkgPath.Val()) prevents repeated computation Edge Case Handling\nRecursive directory search when direct detection fails Special handling for cgo and inline functions This implementation demonstrates how GoFrame combines runtime capabilities with file system analysis to create a robust configuration loading mechanism that works across different environments.\n","date":"2021-08-25T18:47:28+08:00","image":"https://sethix.com/posts/2021082518/cover_hueb6cd1e430342dc04e187be5e015094c_19881_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021082518/","title":"Analyzing How GoFrame Dynamically Loads Configuration Files and the Invocation of runtime.Caller"},{"content":"First note: Using defer inside loops is generally considered a bad practice\nCame across this issue while browsing the community: package main import \u0026#34;fmt\u0026#34; type Test struct { name string } func (t *Test) Close() { fmt.Println(t.name, \u0026#34; closed\u0026#34;) } func main() { ts := []Test{{\u0026#34;a\u0026#34;}, {\u0026#34;b\u0026#34;}, {\u0026#34;c\u0026#34;}} for _, t := range ts { defer t.Close() } } // Output: // c closed // c closed // c closed The output shows three c closed results.\nThe top-voted answer claimed this happens because defer creates an external variable that gets overwritten in the loop. But the code didn\u0026rsquo;t seem to match that explanation, so I investigated further.\nEventually identified the issue as value receivers calling pointer methods. Modified test code:\npackage main import ( \u0026#34;fmt\u0026#34; \u0026#34;unsafe\u0026#34; ) type Test struct { name string } func (t *Test) Close() { fmt.Println(unsafe.Pointer(t), t.name, \u0026#34; closed\u0026#34;) } func main() { // Using pointer slice ts := []*Test{{\u0026#34;a\u0026#34;}, {\u0026#34;b\u0026#34;}, {\u0026#34;c\u0026#34;}} for _, t := range ts { defer t.Close() } } // Output (with pointer addresses): // 0xc000044260 c closed // 0xc000044250 b closed // 0xc000044240 a closed Root cause: Calling pointer methods on values directly.\nOriginal code with address printing:\npackage main import ( \u0026#34;fmt\u0026#34; \u0026#34;unsafe\u0026#34; ) type Test struct { name string } func (t *Test) Close() { fmt.Println(unsafe.Pointer(t), t.name, \u0026#34; closed\u0026#34;) } func main() { ts := []Test{{\u0026#34;a\u0026#34;}, {\u0026#34;b\u0026#34;}, {\u0026#34;c\u0026#34;}} for _, t := range ts { fmt.Println(unsafe.Pointer(\u0026amp;t)) defer t.Close() } } // Output shows same address: // 0xc000044240 // 0xc000044240 // 0xc000044240 // 0xc000044240 c closed // 0xc000044240 c closed // 0xc000044240 c closed Official Explanation from Go Spec: \u0026ldquo;Value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers. However, when the value is addressable, the compiler automatically inserts the address operator to allow calling pointer methods on values.\u0026rdquo;\nKey Points: When calling pointer methods on values in a loop:\nThe compiler uses the same memory address for loop variable t in each iteration All defer statements capture the same memory address The final value at that address becomes c after loop completion When using pointer slices:\nEach element has a distinct memory address defer captures the actual pointer value for each iteration Conclusion: Avoid calling pointer methods on loop variables when using defer. If necessary, create local copies or use pointer slices directly.\n","date":"2021-08-10T13:47:50+08:00","image":"https://sethix.com/posts/2021081013/cover_hu9d9a83ff133d44ba0ddd57899dd8e44a_12534_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021081013/","title":"A Bug When Using defer in Loops in Go"},{"content":"Getting Started (Environment Setup) Create a project directory and add Dockerfile FROM centos:7 # Install dependencies RUN yum -y install gcc gcc-c++ gdb autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers gd gd2 gd-devel gd2-devel perl-CPAN pcre-devel libicu-devel wget # Download specific PHP version RUN wget -O /tmp/php.tar.gz https://www.php.net/distributions/php-7.1.0.tar.gz RUN mkdir ~/php71 \u0026amp;\u0026amp; tar -xvf /tmp/php.tar.gz --strip-components 1 -C ~/php71 # Installation directory: /var/php71 # Source directory: /var/www ################################################################### # 1. Generate Makefile # 2. Compile # 3. Install RUN cd ~/php71 \u0026amp;\u0026amp; \\ ./configure --prefix=/var/php71 --enable-fpm --enable-debug --enable-phpdbg-debug CFLAGS=\u0026#34;-g3 -gdwarf-4\u0026#34; \u0026amp;\u0026amp; \\ make \u0026amp;\u0026amp; \\ make install # Configure PHP \u0026amp; FPM RUN cp ~/php71/php.ini-production /var/php71/lib/php.ini \u0026amp;\u0026amp; \\ cp /var/php71/etc/php-fpm.conf.default /var/php71/etc/php-fpm.conf \u0026amp;\u0026amp; \\ echo $\u0026#39;export PATH=$PATH:/var/php71/bin:/var/php71/sbin\u0026#39; \u0026gt;\u0026gt; ~/.bashrc # Install Nginx for FPM debugging RUN yum -y install epel-release \u0026amp;\u0026amp; \\ yum -y install nginx # Nginx FPM configuration RUN echo $\u0026#39;server {\\n\\ listen 9999;\\n\\ root /var/www;\\n\\ location / {\\n\\ root /var/www;\\n\\ index index.php index.html index.htm;\\n\\ }\\n\\ error_page 500 502 503 504 /50x.html;\\n\\ location ~ \\.php$ {\\n\\ fastcgi_pass 127.0.0.1:9000;\\n\\ fastcgi_index index.php;\\n\\ fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\\n\\ include fastcgi_params;\\n\\ }\\n\\ }\u0026#39; \u0026gt; /etc/nginx/conf.d/fpm.conf # FPM worker configuration RUN echo $\u0026#39;[www]\\n\\ user = nobody\\n\\ group = nobody\\n\\ listen = 127.0.0.1:9000\\n\\ pm = static\\n\\ pm.max_children = 1\u0026#39; \u0026gt; var/php71/etc/php-fpm.d/www.conf Create docker-compose.yml in project directory version: \u0026#39;3\u0026#39; services: centos: build: ./ tty: true cap_add: - SYS_PTRACE working_dir: /var/www volumes: - ./:/var/www ports: - 9999:9999 Build and start container docker-compose up -d \u0026amp;\u0026amp; docker-compose exec centos bash Debugging with GDB docker-compose exec centos bash # Launch TUI mode gdb --tui # Debug executable gdb php # Attach to process gdb --pid=xxx Common Commands Description run Restart program start Step-by-step execution from start list View source code (l) set Set variable values next Step over (n) step Step into (s) break Set breakpoint (b) delete Delete breakpoint finish Exit current function continue Resume execution (c) print Print values (p) quit Exit GDB (q) info View local variables (i) Debugging PHP-FPM Configured with single worker process for easier tracing docker-compose exec centos bash php-fpm nginx # Find worker process ID ps aux | grep fpm gdb --pid=xxx Recommended Tools Use Understand for code navigation Download matching PHP version source code for analysis Adding Extensions (Optional) Requirements: PHP source matching installed version Steps (e.g., curl extension): cd ~/php71/ext/curl /var/php71/bin/phpize ./configure --with-php-config=/var/php71/bin/php-config make \u0026amp;\u0026amp; make install Byte Alignment Example struct A { int a; // 4 bytes char b; // 1 byte short c; // 2 bytes (aligned to 2n) char d; // 1 byte }; /* Memory layout: aaaa b0cc d000 (Total 12 bytes) */ Endianness Big-Endian: 0x1A2B3C4D → 0x1A | 0x2B | 0x3C | 0x4D Little-Endian: 0x1A2B3C4D → 0x4D | 0x3C | 0x2B | 0x1A Variable Storage (ZVAL) typedef union _zend_value { zend_long lval; // Integer double dval; // Double zend_refcounted *counted; // Reference counted types zend_string *str; // String zend_array *arr; // Array // ... other types } zend_value; struct _zval_struct { zend_value value; // Actual value union { struct { ZEND_ENDIAN_LOHI_4( zend_uchar type, // Variable type zend_uchar type_flags, zend_uchar const_flags, zend_uchar reserved) } v; uint32_t type_info; } u1; // ... other fields }; PHP Execution Flow Lexical Analysis: Convert source to tokens Parsing: Generate Abstract Syntax Tree (AST) Compilation: Produce OPcodes Zend VM: Execute OPcodes as machine code Lifecycle CLI Mode php_module_startup → php_request_startup → php_execute_script → php_request_shutdown → php_module_shutdown FPM Mode ┌─────────────────────┐ │ fcgi_accept_request│ └─────────────────────┘ ▲ php_module_startup│ │ php_request_startup │ php_execute_script │ php_request_shutdown │ php_module_shutdown FAQ Struct Hack: char[1] in zend_string enables single memory allocation Typedef Conventions: Global types defined in headers File-local types declared with structs FPM Process Management: Master process manages workers kill -9 on master leaves workers running ","date":"2021-08-03T10:51:57+08:00","image":"https://sethix.com/posts/2021080310/cover_hu9e2688d147c6ae427885dca36a5694c2_23775_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021080310/","title":"PHP Source Code Reading"},{"content":"Today during client-side testing, feedback indicated a slow API response. With the responsible colleague on leave, I investigated the project and confirmed the issue.\nAdded SQL logging in the controller: # SQL logging DB::listen(fn(QueryExecuted $query) =\u0026gt; Log::info($query-\u0026gt;sql)); # Log output [2021-07-22 12:46:15] local.INFO: select * from `albums` where `albums`.`id` = ? and `albums`.`deleted_at` is null limit 1 ... (repeated 24 times) The logs revealed multiple identical queries - a classic N+1 problem caused by missing eager loading Database query pseudocode: class Controller { public function index() { $models = Model::query()-\u0026gt;limit(20)-\u0026gt;get(); return ModelsResource::collection($models); } } class ModelsResource extends JsonResource { public function toArray($request) { return [ \u0026#39;id\u0026#39; =\u0026gt; $this-\u0026gt;id, \u0026#39;name\u0026#39; =\u0026gt; $this-\u0026gt;title, \u0026#39;album_id\u0026#39; =\u0026gt; $this-\u0026gt;album_id, // Problematic line \u0026#39;album_name\u0026#39; =\u0026gt; $this-\u0026gt;album-\u0026gt;title, ]; } } The resource accessed the album relationship without eager loading Solution: Add eager loading $models = Model::query()-\u0026gt;with(\u0026#39;album\u0026#39;)-\u0026gt;limit(20)-\u0026gt;get(); Prevention Strategies Problem detection is costly - better to prevent through automation Implemented HTTP testing with SQL query monitoring in base TestCase: public function json($method, $uri, array $data = [], array $headers = []) { $maxCount = 10; DB::enableQueryLog(); $response = parent::json($method, $uri, $data, $headers); $queries = collect(DB::getQueryLog())-\u0026gt;pluck(\u0026#39;query\u0026#39;); $this-\u0026gt;assertLessThan( $maxCount, $queries-\u0026gt;count(), sprintf(\u0026#34;Endpoint:%s[%s], SQL:%d\\r\\n%s\u0026#34;, $uri, $method, $maxCount, $queries-\u0026gt;implode(\u0026#34;\\r\\n\u0026#34;)) ); DB::flushQueryLog(); return $response; } Enhanced validation using unique query comparison: $duplicateQueries = $queries-\u0026gt;count() - $queries-\u0026gt;unique()-\u0026gt;count(); $this-\u0026gt;assertLessThan($maxDuplicates, $duplicateQueries, \u0026#34;Excessive duplicate queries\u0026#34;); Route coverage validation via custom test suite: \u0026lt;testsuite name=\u0026#34;End\u0026#34;\u0026gt; \u0026lt;file\u0026gt;tests/EndApiTest.php\u0026lt;/file\u0026gt; \u0026lt;/testsuite\u0026gt; Route validation test class: class EndApiTest extends TestCase { public function testRoutes() { $router = $this-\u0026gt;app-\u0026gt;make(Router::class); $definedRoutes = collect($router-\u0026gt;getRoutes()-\u0026gt;getRoutes()); $definedRoutes-\u0026gt;each(function ($route) { $this-\u0026gt;assertContains( $route-\u0026gt;uri(), self::$testedRoutes, \u0026#34;Untested route: {$route-\u0026gt;uri()}\u0026#34; ); }); } } Key Takeaways\nAutomated testing with query monitoring and route coverage validation helps prevent performance regressions and ensures API reliability. The system now automatically:\nLimits total SQL queries per endpoint Detects duplicate queries Enforces 100% route test coverage Provides immediate feedback during development This approach reduces manual verification efforts while maintaining code quality standards.\n","date":"2021-07-22T15:08:54+08:00","image":"https://sethix.com/posts/2021072215/cover_hue861a15384269acdd5e39487b5c3f91a_2999_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021072215/","title":"A Slow API Incident Leading to Database Query Testing and Fully Automated API Test Assertions"},{"content":"First, let\u0026rsquo;s look at the Git flow diagram:\nGit flow The flowchart might seem complex at first glance. We\u0026rsquo;ll use Sourcetree to help understand the process. Getting Started (Screenshots show Sourcetree operations, commands show actual execution) Create a new project log-service mkdir log-service cd log-service git init Sourcetree Initialize project configuration Set up framework selection, project description, etc. Replace the following commands with your actual operations: echo \u0026#34;## log-service\u0026#34; \u0026gt; README.md git add README.md git commit -m \u0026#34;init project\u0026#34; Initialize workflow (git flow init) Both red and green arrows in the image can initialize a workflow Sourcetree Create a new feature (git flow feature start show-log) We\u0026rsquo;ll create a feature show-log This is checked out from the develop branch Sourcetree Sourcetree Commit code Simulate some operations with the following code: echo \u0026#34;collect show log\u0026#34; \u0026gt; show.log git add show.log git commit -m \u0026#34;add: show log\u0026#34; Complete the feature (git flow feature finish show-log) After completion: show-log branch merges into develop show-log branch gets deleted Sourcetree Sourcetree Sourcetree Simulating collaborative development conflicts Add click logs with two developers working on click-log-1 and click-log-2 git flow feature start click-log-1 git flow feature start click-log-2 git checkout feature/click-log-1 echo \u0026#34;click 1 log\u0026#34; \u0026gt; click.log git add click.log git commit -m \u0026#34;add: click log\u0026#34; git checkout feature/click-log-2 echo \u0026#34; first \\n click 2 log\u0026#34; \u0026gt; click.log git add click.log git commit -m \u0026#34;add: click log\u0026#34; Complete feature operations: git flow feature finish click-log-1 git flow feature finish click-log-2 The first operation succeeds normally The second operation reports conflicts since both modified click.log The click-log-2 branch remains after failed merge The actual git flow feature finish process: git checkout develop git merge feature/\u0026lt;feature_name\u0026gt; git branch -d feature/\u0026lt;feature_name\u0026gt; Resolve conflicts manually, commit changes, then delete branch: git branch -d feature/click-log-2 Git Sourcetree Create a release version (git flow release start v1.0.0) Checked out from develop branch\nSourcetree Sourcetree If a bug is found during testing: Fix directly in release branch Simulate release bug fix: echo \u0026quot;release v1.0.0\u0026quot; \u0026gt; release.log git add release.log git commit -m \u0026quot;fix: release bug\u0026quot; Complete release version (git flow release finish v1.0.0) After testing/bug fixing: Merges into both develop and master\nSourcetree Sourcetree Create a hotfix (git flow hotfix start click-log) Sourcetree Sourcetree Emergency fix for production click log issue Checked out from master branch Simulate hotfix: echo \u0026quot;fix click log\u0026quot; \u0026gt;\u0026gt; click.log git add click.log git commit -m \u0026quot;fix: click log\u0026quot; Complete hotfix (git flow hotfix finish click-log) Automatically merges into develop and master\nSourcetree Important Notes Remote repository connection For remote repositories, use publish operation after start git flow feature publish \u0026lt;feature_name\u0026gt; does: Creates remote feature/\u0026lt;feature_name\u0026gt; branch Sets local branch to track remote Pushes uncommitted changes To push or not to push Push if feature requires collaboration No need if working solo Merging considerations In team collaboration:\nRepository admin should create master branch and initialize GitFlow locally before pushing both master and develop to remote (with write protection on master) Collaborators clone project and initialize GitFlow with same configs Collaborators push features to develop Admin handles release branches and versioning References The Ultimate Guide to Gitflow Usage\nGit Flow Workflow Implementation in Sourcetree\nhttps://www.git-tower.com\n","date":"2021-07-21T12:12:09+08:00","image":"https://sethix.com/posts/2021072112/cover_hucf9f513bd229f407ab0800c5c4ae24b6_75273_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021072112/","title":"Using Git flow in Sourcetree"},{"content":" Using laravel-admin for backend development, we added a notification bell in the top-right corner Laravel Admin Notification Interface As shown above, clicking the bell icon should clear notifications and refresh the current page. Implemented using laravel-admin\u0026rsquo;s action: \u0026lt;?php namespace App\\Admin\\Actions\\Custom; use Encore\\Admin\\Actions\\Action; use Illuminate\\Http\\Request; class MarkNotificationRead extends Action { protected $selector = \u0026#39;.mark-notification-read\u0026#39;; public function handle(Request $request) { // forget notifications return $this-\u0026gt;response()-\u0026gt;success(\u0026#34;Marked all as read\u0026#34;)-\u0026gt;refresh(); } public function html() { // get notifications $count = 1; $countText = \u0026#34;\u0026lt;span class=\\\u0026#34;label label-danger\\\u0026#34;\u0026gt;{$count}\u0026lt;/span\u0026gt;\u0026#34;; return \u0026#34;\u0026lt;li title=\u0026#39;Click to mark as read\u0026#39;\u0026gt; \u0026lt;a href=\\\u0026#34;#\\\u0026#34; class=\u0026#39;mark-notification-read\u0026#39;\u0026gt; \u0026lt;i data-count=\u0026#39;{$count}\u0026#39; id=\u0026#39;notification\u0026#39; class=\\\u0026#34;fa fa-bell fa-rotate-0\\\u0026#34;\u0026gt;\u0026lt;/i\u0026gt; {$countText} \u0026lt;/a\u0026gt; \u0026lt;/li\u0026gt;\u0026#34;; } } The pseudo-code above implements the notification feature. However, laravel-admin\u0026rsquo;s PJAX implementation only refreshes content areas, leaving the bell badge unchanged. Attempted Solutions:\nTried disabling PJAX using \\Admin::disablePjax(); in handler - ineffective (should be applied at page level) Overrode the handleActionPromise method in the Action class: public function handleActionPromise() { $resolve = \u0026lt;\u0026lt;\u0026lt;\u0026#39;SCRIPT\u0026#39; var actionResolver = function (data) { // ... [original code] if (then.action == \u0026#39;refresh\u0026#39;) { // Added this critical line window.location.reload(); return; } // ... [remaining code] SCRIPT; \\Encore\\Admin\\Admin::script($resolve); return \u0026lt;\u0026lt;\u0026lt;\u0026#39;SCRIPT\u0026#39; process.then(actionResolver).catch(actionCatcher); SCRIPT; } Comparison with Dcat Admin:\nNotably, Dcat Admin provides better extensibility through overridable methods:\nprotected function resolverScript() { return \u0026lt;\u0026lt;\u0026lt;\u0026#39;JS\u0026#39; function (target, results) { // Custom refresh handling window.location.reload(); } JS; } Key Takeaways Avoid getting tunnel-visioned by perceived constraints (PJAX limitations in this case) When stuck, consider re-examining parent class capabilities before complex workarounds Modern admin frameworks often provide extension points - explore inheritance hierarchies before reinventing wheels This experience demonstrates how stepping back from conventional thinking patterns can reveal simpler solutions hidden in framework mechanics.\n","date":"2021-07-07T13:04:58+08:00","image":"https://sethix.com/posts/2021070713/cover_hu9a18e5c167e5c2119d2a08407a90c3c9_34786_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021070713/","title":"Solving Custom Page Refresh Issue with Admin PJAX by Breaking Out of Conventional Thinking"},{"content":"Environment PHP_VERSION=7.4 laravel/framework: ^7.0 Static Variables In many programming languages, static variables are defined as variables that: Have the same lifecycle as the program Are initialized only once However, in PHP\u0026rsquo;s common runtime environment (php-fpm mode), processes get recycled after each request, so static variables don\u0026rsquo;t persist in memory (only effective during the current request) Official PHP documentation states: \u0026ldquo;Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.\u0026rdquo; https://www.php.net/manual/zh/language.variables.scope.php\nPreface The project contained the following pseudo-code logic: Since json_data in the database is a JSON string, we used the static modifier to avoid repeated parsing \u0026lt;?php namespace App\\Models; use Illuminate\\Database\\Eloquent\\Model; class AttributeRequestLog extends Model { public function getJsonData($key) { static $jsonData; if (is_null($jsonData)) { $jsonData = json_decode($this-\u0026gt;attributes[\u0026#39;json_data\u0026#39;], true); } return $jsonData[$key] ?? null; } } The code worked fine until we implemented queues for asynchronous tasks. After queue implementation, colleagues reported abnormal data. Log analysis revealed issues in queue task logging, which was ultimately traced back to this static variable usage.\nLaravel queues run in CLI mode as long-running processes Queue workers load code on startup and keep it in memory until process termination Source Code Analysis Queue startup command: php artisan queue:work The entry file src\\Illuminate\\Queue\\Console\\WorkCommand.php extends Illuminate\\Console\\Command, running the handle method when executed Laravel Laravel The worker retrieves queue driver configuration and passes a once parameter to determine if it should process a single job Examining the daemon method in src\\Illuminate\\Queue\\Worker.php:\nLaravel The first three lines handle process signal listening $lastRestart gets a timestamp from cache for graceful shutdown (reset by php artisan queue:restart) Uses an infinite loop to keep the process alive Checks for maintenance mode and other preconditions getNextJob fetches the next task from queue driver (Redis, Database, etc.) registerTimeoutHandler handles task timeout using async signals if supported Processes jobs or sleeps when no tasks available\nLaravel Laravel The fire method uses reflection to invoke job handlers\nLaravel stopIfNecessary checks for termination conditions The static variable $jsonData persists across multiple queue jobs Since queue workers are long-running processes: Static variables retain values between different job executions Subsequent jobs may receive cached/stale data from previous executions This caused data contamination between different queue tasks Solution Avoid static variables in queue-related classes Use class properties with proper reset mechanisms Implement __destruct() to clear cached data Alternative implementation without static caching: public function getJsonData($key) { if (!isset($this-\u0026gt;jsonDataCache)) { $this-\u0026gt;jsonDataCache = json_decode($this-\u0026gt;attributes[\u0026#39;json_data\u0026#39;], true); } return $this-\u0026gt;jsonDataCache[$key] ?? null; } public function __destruct() { unset($this-\u0026gt;jsonDataCache); } Key Takeaways Static variables behave differently in long-running processes vs. request-response cycles Queue workers maintain application state between jobs Always consider process lifecycle when using: Static variables Singleton patterns Class-level caching Implement proper cleanup mechanisms for resource-intensive operations ","date":"2021-07-06T12:43:13+08:00","image":"https://sethix.com/posts/2021070612/cover_hub37a0bfb335664f0b241cc4b1b2dcb53_61846_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021070612/","title":"A Bug Caused by Static Variables in Laravel Queues"},{"content":"Debugging Steps The cron jobs in laradock are executed in the workspace container. Check logs using: docker-compose logs -f workspace Sample log output:\nJul 2 12:26:59 9b6ec4d18dd1 syslog-ng[12]: syslog-ng starting up; version=\u0026#39;3.13.2\u0026#39; workspace_1 | *** Booting runit daemon... workspace_1 | *** Runit started as PID 20 workspace_1 | Jul 2 12:27:00 9b6ec4d18dd1 cron[23]: (CRON) INFO (pidfile fd = 3) ... Enter the container: docker-compose exec workspace bash Test cron job execution without suppressing output: /usr/bin/php /var/www/artisan schedule:run Permission Issues Logs in /storage/logs showed permission errors when created by root user. Fix permissions: chmod -R 0777 storage Access container as laradock user: docker-compose exec --user=laradock workspace bash Critical Update (2021-07-02 11:19:56 Friday) Discovered cron jobs failing due to Windows line ending characters (^M):\nLog output revealed hidden characters: workspace_1 | Jul 2 03:20:01 fac0b255876a CRON[350]: (laradock) CMD (/usr/bin/php...2\u0026gt;\u0026amp;1^M) Solution: Remove CRLF line endings from cron configurations Rebuild container: docker-compose build workspace docker-compose stop workspace \u0026amp;\u0026amp; docker-compose up -d workspace Multi-Server Deployment Strategy To prevent duplicate cron job execution:\nRemove Laravel scheduler from laradock/workspace/crontab/laradock\nUse php-worker container instead\nEnable scheduler:\ncp laravel-scheduler.conf.example laravel-scheduler.conf docker-compose restart php-worker Verify operation:\ndocker-compose exec php-worker sh /etc/supervisor/conf.d # supervisorctl status Expected output:\nlaravel-scheduler:laravel-scheduler_00 RUNNING pid 9, uptime 2:14:33 ","date":"2021-07-02T11:25:44+08:00","image":"https://sethix.com/posts/2021070211/cover_hu91fe5e90503617fb030af5bf27a46842_24915_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021070211/","title":"A Lesson Learned from Laradock Cron Job Failures"},{"content":" Previous article: Speed Up Your Service Performance by Reducing Service Provider Boot Time 2.0 A reader mentioned errors when directly removing the View service. This article demonstrates how to properly remove the View service. Step-by-Step Guide 1. Create a New Laravel Project composer create-project laravel/laravel=7.* laravel-demo 2. Modify the Default Route Edit routes/web.php to return JSON instead of a view:\nRoute::get(\u0026#39;/\u0026#39;, function () { return [ \u0026#39;code\u0026#39; =\u0026gt; 200, \u0026#39;msg\u0026#39; =\u0026gt; \u0026#39;hello\u0026#39; ]; }); 3. Disable the View Service Provider Comment out the View service provider in config/app.php:\n// \u0026#39;providers\u0026#39; =\u0026gt; [ // ... // Illuminate\\View\\ViewServiceProvider::class, // ... // ], 4. Handle Ignition Package Dependency Add to composer.json to prevent automatic registration:\n\u0026#34;extra\u0026#34;: { \u0026#34;laravel\u0026#34;: { \u0026#34;dont-discover\u0026#34;: [ \u0026#34;facade/ignition\u0026#34; ] } }, Then run:\ncomposer dump-autoload 5. Fix Middleware Dependency Comment out the view-related middleware in app/Http/Kernel.php:\n// \\App\\Http\\Middleware\\ShareErrorsFromSession::class, 6. Custom Error Handling Modify app/Exceptions/Handler.php to handle errors without views:\npublic function render($request, Throwable $exception) { $code = 500; if ($exception instanceof NotFoundHttpException) { $code = 404; } return (new Response(json_encode([ \u0026#39;code\u0026#39; =\u0026gt; $code, \u0026#39;msg\u0026#39; =\u0026gt; $exception-\u0026gt;getMessage() ])))-\u0026gt;withHeaders([\u0026#39;Content-Type\u0026#39; =\u0026gt; \u0026#39;application/json\u0026#39;]); } Handling Mixed Environments (API + Admin) For projects using both API and admin panels:\nAdd a configuration flag in config/app.php: \u0026#39;enable_admin\u0026#39; =\u0026gt; env(\u0026#39;ENABLE_ADMIN\u0026#39;, false), Conditionally load service providers: \u0026#39;providers\u0026#39; =\u0026gt; [ ... config(\u0026#39;app.enable_admin\u0026#39;) ? Illuminate\\View\\ViewServiceProvider::class : null, ... ], Key Points Always check dependencies of third-party packages Use composer.json\u0026rsquo;s dont-discover for problematic packages Verify middleware dependencies Implement custom error handling for API-only responses By following these steps, you can safely remove the View service while maintaining API functionality. The final application will return JSON responses without any view-related components, reducing memory usage and improving performance.\n","date":"2021-05-26T16:54:46+08:00","image":"https://sethix.com/posts/2021052616/cover_hub37a0bfb335664f0b241cc4b1b2dcb53_61846_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021052616/","title":"How to Remove the Core Service - Views in Laravel"},{"content":"Performance has always been one of the most discussed topics in Laravel, yet it has brought fresh perspectives to many PHP developers. Let\u0026rsquo;s optimize this framework once again.\nFundamentals (Common Knowledge) Use Redis drivers for caching, sessions, and queues Framework built-in caching: Route caching: php artisan route:cache Configuration caching: php artisan config:cache Implement caching based on API idempotency Upgrades OPcache: Enable it without hesitation Set opcache.validate_timestamps=0 to prevent automatic code updates in production (similar to compiled languages). Restart php-fpm after each deployment Reference: Best Config for Zend OPcache Remove Unnecessary Middleware Remove CORS middleware if your API only serves mobile apps Remove default API rate limiting middleware if unsuitable for your scenario Reduce Service Providers Disable unnecessary services for pure API projects: View services Session services Password reset services Let\u0026rsquo;s focus on hybrid projects containing both API and Admin interfaces (using full-stack frameworks like Laravel-admin or Dcat Admin).\nSince Laravel 5.5 introduced package auto-discovery, we can optimize service providers by:\nList registered service providers: php artisan package:discover Discovered Package: dcat/laravel-admin Discovered Package: facade/ignition ... Disable auto-discovery for specific packages in composer.json: \u0026#34;extra\u0026#34;: { \u0026#34;laravel\u0026#34;: { \u0026#34;dont-discover\u0026#34;: [\u0026#34;dcat/laravel-admin\u0026#34;] } } Conditionally register service providers in AppServiceProvider.php: public function boot() { if (config(\u0026#39;admin.enable\u0026#39;)) { AliasLoader::getInstance()-\u0026gt;alias(\u0026#39;Admin\u0026#39;, Admin::class); $this-\u0026gt;app-\u0026gt;register(AdminServiceProvider::class); } } This optimization achieved 40% performance improvement (tested on 2vCPU/4GB machine with OPcache enabled):\nService Optimization Q\u0026amp;A: Disabling View Services Comment out in config/app.php: // Illuminate\\View\\ViewServiceProvider::class, // Illuminate\\Notifications\\NotificationServiceProvider::class, // Illuminate\\Pagination\\PaginationServiceProvider::class Modify Exceptions/Handler.php for API error handling: public function render($request, Exception $exception) { if ($request-\u0026gt;is(\u0026#39;api*\u0026#39;)) { return (new Response(json_encode([ \u0026#39;code\u0026#39; =\u0026gt; 500, \u0026#39;msg\u0026#39; =\u0026gt; $exception-\u0026gt;getMessage() ])))-\u0026gt;withHeaders([\u0026#39;Content-Type\u0026#39; =\u0026gt; \u0026#39;application/json\u0026#39;]); } return parent::render($request, $exception); } ","date":"2021-05-25T12:08:42+08:00","image":"https://sethix.com/posts/2021052512/cover_huc8ab171a934f0de687c88b465bd668e3_34365_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021052512/","title":"Optimizing Laravel Performance by Reducing Service Providers Boot 2.0"},{"content":" For beginners, I recommend these introductory tutorials first:\nAssembly Language Quick Start\nAssembly Language Primer (Ruan Yifeng) Be sure to read Mr. Ruan\u0026rsquo;s tutorial in detail Common Identifiers (See Registers and Operation Instructions tables at the end for more) $ prefix followed by numbers represents a constant value FUNCDATA and PCDATA instructions contain garbage collector information generated by the compiler PCDATA syntax: PCDATA tableid, tableoffset PCDATA has two parameters: table type and table offset. Current implementations include PCDATA_StackMapIndex and PCDATA_InlTreeIndex table types. Both contain code location info (file path, line numbers, function info), with PCDATA_InlTreeIndex used for inlined functions.\nFUNCDATA tableid, tableoffset Similar to PCDATA: first parameter is table type, second is table offset. Current implementations define three FUNC table types: FUNCDATA_ArgsPointerMaps (function argument pointers), FUNCDATA_LocalsPointerMaps (local pointers), and FUNCDATA_InlTree (inlined function pointers). These tables help Go\u0026rsquo;s garbage collector track pointer lifecycles.\nOperations Below C:\\Users\\seth-shi\u0026gt; cat main.go package main func Add(x, y int) int { return x + y } C:\\Users\\seth-shi\u0026gt; go build -gcflags -S main.go Comments starting with ## are my understanding/research results. [] indicates areas needing further study # command-line-arguments ## Defines process \u0026#34;\u0026#34;.Add with args=0x0 locals=0x18 (hex 24) [Need to study size/args] \u0026#34;\u0026#34;.Add STEXT nosplit size=19 args=0x18 locals=0x0 funcid=0x0 ## TEXT pseudo-operation defines process at \u0026#34;\u0026#34;.Add(SB) address ## $0-24 indicates stack size (3*8 bytes for ints?) [Needs verification] ## ABIInternal = Application Binary Interface Internal 0x0000 00000 (C:\\Users\\seth-shi\\main.go:3) TEXT \u0026#34;\u0026#34;.Add(SB), NOSPLIT|ABIInternal, $0-24 ## GC info (ignore) 0x0000 00000 (C:\\Users\\seth-shi\\main.go:3) FUNCDATA $0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB) 0x0000 00000 (C:\\Users\\seth-shi\\main.go:3) FUNCDATA $1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB) ## Move stack+16 to AX [Need to verify stack direction] 0x0000 00000 (C:\\Users\\seth-shi\\main.go:4) MOVQ \u0026#34;\u0026#34;.y+16(SP), AX ## Move stack+8 to CX 0x0005 00005 (C:\\Users\\seth-shi\\main.go:4) MOVQ \u0026#34;\u0026#34;.x+8(SP), CX ## Add CX to AX 0x000a 00010 (C:\\Users\\seth-shi\\main.go:4) ADDQ CX, AX ## Store result at stack+24 0x000d 00013 (C:\\Users\\seth-shi\\main.go:4) MOVQ AX, \u0026#34;\u0026#34;.~r2+24(SP) ## Return 0x0012 00018 (C:\\Users\\seth-shi\\main.go:4) RET 0x0000 48 8b 44 24 10 48 8b 4c 24 08 48 01 c8 48 89 44 H.D$.H.L$.H..H.D 0x0010 24 18 c3 $.. go.cuinfo.packagename.main SDWARFCUINFO dupok size=0 0x0000 6d 61 69 6e main go.string.\u0026#34;0w\\xaf\\f\\x92t\\b\\x02A\\xe1\\xc1\\a\\xe6\\xd6\\x18\\xe6path\\tcommand-line-arguments\\nmod\\tseth\\t(devel)\\t\\n\\xf92C1\\x86\\x18 r\\x00\\x82B\\x10A\\x16\\xd8\\xf2\u0026#34; SRODATA dupok size=78 0x0000 30 77 af 0c 92 74 08 02 41 e1 c1 07 e6 d6 18 e6 0w...t..A....... 0x0010 70 61 74 68 09 63 6f 6d 6d 61 6e 64 2d 6c 69 6e path.command-lin 0x0020 65 2d 61 72 67 75 6d 65 6e 74 73 0a 6d 6f 64 09 e-arguments.mod. 0x0030 73 65 74 68 09 28 64 65 76 65 6c 29 09 0a f9 32 seth.(devel)...2 0x0040 43 31 86 18 20 72 00 82 42 10 41 16 d8 f2 C1.. r..B.A... \u0026#34;\u0026#34;..inittask SNOPTRDATA size=24 0x0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 0x0010 00 00 00 00 00 00 00 00 ........ runtime.modinfo SDATA size=16 0x0000 00 00 00 00 00 00 00 00 4e 00 00 00 00 00 00 00 ........N....... rel 0+8 t=1 go.string.\u0026#34;0w\\xaf\\f\\x92t\\b\\x02A\\xe1\\xc1\\a\\xe6\\xd6\\x18\\xe6path\\tcommand-line-arguments\\nmod\\tseth\\t(devel)\\t\\n\\xf92C1\\x86\\x18 r\\x00\\x82B\\x10A\\x16\\xd8\\xf2\u0026#34;+0 type..importpath.unsafe. SRODATA dupok size=9 0x0000 00 00 06 75 6e 73 61 66 65 ...unsafe gclocals·33cdeccccebe80329f1fdbee7f5874cb SRODATA dupok size=8 0x0000 01 00 00 00 00 00 00 00 ........ # command-line-arguments runtime.main_main·f: function main is undeclared in the main package Registers Mnemonic Name Purpose AX Accumulator Register Data storage for arithmetic, operands, results, and temporary addresses BX Base Register Memory access address storage CX Count Register Counter values DX Data Register Data transfer and I/O port addresses SP Stack Pointer symbol+offset(SP) = Go pseudo-register; offset(SP) = hardware register BP Base Pointer Stack base address before function entry SB Static Base Pointer Go pseudo-register. foo(SB) = memory address; foo+4(SB) = 4-byte offset FP Frame Pointer Go pseudo-register. References function parameters via symbol+offset(FP) SI Source Index Source operand offset DI Destination Index Destination operand offset Operation Instructions Mnemonic Type Purpose Example MOVQ Data Transfer Move data MOVQ 48, AX moves 48 to AX LEAQ Address Transfer Load effective address LEAQ AX, BX loads AX address into BX ADDQ Arithmetic Add and assign ADDQ BX, AX stores BX+AX in AX SUBQ Arithmetic Subtract and assign (Similar to ADDQ) IMULQ Arithmetic Unsigned multiply (Similar to ADDQ) IDIVQ Arithmetic Unsigned divide IDIVQ CX divides AX by CX, result in AX CMPQ Comparison Compare values CMPQ SI, CX compares registers CALL Control Flow Function call CALL runtime.printnl(SB) calls println JMP Control Flow Unconditional jump JMP 389 jumps to 0x0185 JLS Control Flow Conditional jump (less than) JLS 389 jumps if SI \u0026lt; CX References A Morning Spent on Golang\u0026rsquo;s Plan9 Assembly\nGo Compiler Tools: Plan9 Assembly\nGo Plan9 Assembly Primer - Bridging Application and Low-Level [Go Night Reading]\n","date":"2021-05-11T18:33:55+08:00","image":"https://sethix.com/posts/2021051118/cover_hua5ee51293b931637e245030a3b073fc9_30151_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021051118/","title":"Learning Go's Plan 9 Assembly"},{"content":"Recently while working on an advertising service that requires cross-application data transmission between backend services (PHP + Go), we chose symmetric encryption for implementation.\nCommon Pitfalls Key Length Errors may occur if using a 32-bit key (since documentation states valid lengths are 16, 24, 32)\nAES-128: Requires 16-byte key\nAES-192: Requires 24-byte key\nAES-256: Requires 32-byte key\nAlways match key length to the selected algorithm.\nPadding Algorithm Easily overlooked in PHP due to simple usage: $text = \u0026#34;String to encrypt\u0026#34;; // Key length must match algorithm requirements $key = \u0026#34;2bfbd593bb32b2b9\u0026#34;; // AES-128-ECB depends on chosen algorithm openssl_encrypt($text, \u0026#39;AES-128-ECB\u0026#39;, $key); The above produces base64-encoded output by default. For raw binary data: openssl_encrypt($text, \u0026#39;AES-128-ECB\u0026#39;, $key, OPENSSL_RAW_DATA); The fourth parameter can also specify custom padding. Inter-Service Debugging Tips Avoid direct debugging between two services initially. First validate encryption/decryption using online tools, then proceed with inter-service testing. ","date":"2021-05-11T12:41:39+08:00","image":"https://sethix.com/posts/2021051112/cover_hu620fac4d17d87c0e43ec32bf387c48d3_33431_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021051112/","title":"Cross-Service Data Verification Using AES Algorithm"},{"content":"Xshell Recently, using the command:\nssh-keygen to generate a private key could not be imported into Xshell for use.\nssh-keygen Use the following new command to generate keys:\nrsa indicates using RSA encryption\nssh-keygen -m PEM -t rsa Sourcetree If keys are configured but Sourcetree consistently fails to operate remote repositories Go to Tools -\u0026gt; Options -\u0026gt; General\nSourcetree Select OpenSSH and choose the id_rsa private key under your user directory.\n","date":"2021-03-19T16:23:36+08:00","image":"https://sethix.com/posts/2021031916/cover_hu9e7de9f7afbf82b8e7f823c3339f3214_8272_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021031916/","title":"SSH-Keygen Generated Keys Cannot Be Used for Remote Connections, Sourcetree Unable to Operate Remote Repositories"},{"content":"Today, our team encountered a bug reported in the group chat. After cloning the project locally, I spent some time reproducing the issue.\nCode Overview The following code causes the first item removal to convert a Collection into an object (JSON data): protected function transformJson($items) { return Collection::make($items) - -\u0026gt;values() -\u0026gt;where(\u0026#39;_remove_\u0026#39;, \u0026#39;0\u0026#39;) + -\u0026gt;values() -\u0026gt;map(fn($item) =\u0026gt; Arr::except($item, \u0026#39;_remove_\u0026#39;)) -\u0026gt;toJson(); In the API data retrieval logic, this function call pattern caused issues: public function index() { // $json={\u0026#34;1\u0026#34;:{\u0026#34;id\u0026#34;: 2}} $data = Collection::make($json); // Filtering converts indexes to 0-based $index = $this-\u0026gt;getRandomAd($data, [1]); // Returns null due to original key mismatch return $data-\u0026gt;get($index); } protected function getRandomAd(Collection $data, $notIn=[]) { $index = -1; if (count($notIn) \u0026gt; 0) { $data = $data-\u0026gt;filter(fn($item) =\u0026gt; !in_array($item[\u0026#39;id\u0026#39;], $notIn))-\u0026gt;values(); } // Now working with 0-indexed array foreach ($data as $index =\u0026gt; $item) { if ($item[\u0026#39;id\u0026#39;]) { return $index; } } // Returns filtered index incompatible with original collection return $index; } Root Causes • Late-added filtering logic in getRandomAd unexpectedly converted the Collection to a 0-indexed array\n• Non-destructive operations (filter + values) created a new collection instead of modifying the original\n• Index mismatch occurred between the filtered 0-based indexes and original collection keys\n• Reference semantics were broken by reassignment rather than using mutable operations like transform\nKey Insight: Using transform instead of map would have avoided this bug by modifying the original collection directly.\n","date":"2021-03-14T12:07:42+08:00","image":"https://sethix.com/posts/2021031412/cover_hu255fa94b8bc45bf1d25bfad9197f46cf_62658_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021031412/","title":"A Bug Caused by Combined Array Index Changes and Reference Parameters in PHP"},{"content":" Recently while solving a problem on LeetCode (finding the kth largest number), I needed to sort an array. Realized I only knew basic sorting algorithms like Bubble Sort and Insertion Sort. Then I reviewed Quick Sort through animated examples online, and implemented my own version (code is similar to common implementations): // 1. Select a pivot element (can choose the first element or random element) // 2. Use two pointers starting from both ends, right pointer moves first // 3. Right pointer stops when finding element smaller than pivot // 4. Left pointer then moves and stops when finding element larger than pivot // 5. Swap elements found in steps 3 \u0026amp; 4 // 6. Repeat 3-5 until pointers meet // 7. When pointers collide, perform final swap to ensure correctness func quickSort(data []int, left, right int) { if left \u0026gt;= right { return } pivotIndex := partition(data, left, right) quickSort(data, left, pivotIndex-1) quickSort(data, pivotIndex+1, right) } func partition(data []int, left, right int) int { pivotIndex := left pivot := data[pivotIndex] for left != right { // Right pointer moves first if data[right] \u0026gt; pivot { right-- continue } // Left pointer moves only when \u0026lt;= pivot // (prevents infinite loop with equal elements) if data[left] \u0026lt;= pivot { left++ continue } // Swap mismatched pairs data[left], data[right] = data[right], data[left] } // Final swap to place pivot in correct position data[left], data[pivotIndex] = data[pivotIndex], data[left] return left } LeetCode Screenshot Key translation notes:\nPreserved code comments with technical terms (pivot, pointers, swap) Kept code identifiers unchanged (quickSort, partition, data) Translated algorithm logic descriptions accurately Maintained proper Markdown/Hugo frontmatter format Retained LeetCode/Go as proper nouns Converted Chinese quotation marks to English equivalents Preserved image/URL paths while translating alt text ","date":"2021-01-29T15:24:18+08:00","image":"https://sethix.com/posts/2021012915/cover_hufd2e66ca49a92e9775e924a841c7e054_2374_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021012915/","title":"I Have a Technique Called Quick Sort"},{"content":" Today, our product team reported an issue: why can\u0026rsquo;t we find relevant data when searching for \u0026ldquo;be\u0026rdquo; in our system? There are indeed videos containing phrases like \u0026ldquo;i want to be xxx\u0026rdquo; in our database Stop Words We use the IK Analyzer. After checking GitHub issues, we learned about stop words. Reference: Stop words explanation\nSolution: Remove the specific stop word\nNavigate to Elasticsearch root directory (Docker container in my case) cd /usr/share/elasticsearch Access IK Analyzer configuration (located in config directory for newer versions) cd config/analysis-ik Check the English stop words file: # cat stopword.dic a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with Remove the target stop word \u0026ldquo;be\u0026rdquo; Restart Elasticsearch Reindex the documents. Now searches for \u0026ldquo;be\u0026rdquo; will return relevant results Custom Dictionary Analyze current tokenization: POST /_analyze { \u0026#34;analyzer\u0026#34;: \u0026#34;ik_max_word\u0026#34;, \u0026#34;text\u0026#34;: \u0026#34;q宠大乱斗\u0026#34; } // Response: { \u0026#34;tokens\u0026#34;: [ {\u0026#34;token\u0026#34;: \u0026#34;q\u0026#34;, \u0026#34;type\u0026#34;: \u0026#34;ENGLISH\u0026#34;, ...}, {\u0026#34;token\u0026#34;: \u0026#34;宠大\u0026#34;, \u0026#34;type\u0026#34;: \u0026#34;CN_WORD\u0026#34;, ...}, {\u0026#34;token\u0026#34;: \u0026#34;大乱斗\u0026#34;, \u0026#34;type\u0026#34;: \u0026#34;CN_WORD\u0026#34;, ...}, {\u0026#34;token\u0026#34;: \u0026#34;大乱\u0026#34;, \u0026#34;type\u0026#34;: \u0026#34;CN_WORD\u0026#34;, ...}, {\u0026#34;token\u0026#34;: \u0026#34;斗\u0026#34;, \u0026#34;type\u0026#34;: \u0026#34;CN_CHAR\u0026#34;, ...} ] } Modify IKAnalyzer.cfg.xml: \u0026lt;!-- Before --\u0026gt; \u0026lt;entry key=\u0026#34;ext_dict\u0026#34;\u0026gt;\u0026lt;/entry\u0026gt; \u0026lt;!-- After --\u0026gt; \u0026lt;entry key=\u0026#34;ext_dict\u0026#34;\u0026gt;custom_words.dic\u0026lt;/entry\u0026gt; Create custom dictionary file: # cat custom_words.dic q宠 Restart Elasticsearch Verify new tokenization: { \u0026#34;tokens\u0026#34;: [ {\u0026#34;token\u0026#34;: \u0026#34;q宠\u0026#34;, \u0026#34;type\u0026#34;: \u0026#34;CN_WORD\u0026#34;, ...}, {\u0026#34;token\u0026#34;: \u0026#34;q\u0026#34;, \u0026#34;type\u0026#34;: \u0026#34;ENGLISH\u0026#34;, ...}, {\u0026#34;token\u0026#34;: \u0026#34;宠大\u0026#34;, \u0026#34;type\u0026#34;: \u0026#34;CN_WORD\u0026#34;, ...}, {\u0026#34;token\u0026#34;: \u0026#34;大乱斗\u0026#34;, \u0026#34;type\u0026#34;: \u0026#34;CN_WORD\u0026#34;, ...}, {\u0026#34;token\u0026#34;: \u0026#34;大乱\u0026#34;, \u0026#34;type\u0026#34;: \u0026#34;CN_WORD\u0026#34;, ...}, {\u0026#34;token\u0026#34;: \u0026#34;斗\u0026#34;, \u0026#34;type\u0026#34;: \u0026#34;CN_CHAR\u0026#34;, ...} ] } Now the custom term \u0026ldquo;q宠\u0026rdquo; is properly recognized in tokenization results.\n","date":"2021-01-13T16:12:02+08:00","image":"https://sethix.com/posts/2021011316/cover_hu4ab6886050842d6cc7588c7f314fb7e7_15478_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021011316/","title":"Stop Words and Custom Dictionaries in Elasticsearch"},{"content":" For developers transitioning from PHP, some common questions arise: How can sequential requests affect each other? In many programming languages, this could be easily achieved using global variables However, in PHP, each request is completely independent This design has both advantages and disadvantages: Downside: Requires reloading code and configurations on each request Advantage: Automatic memory cleanup after request completion eliminates leakage concerns While PHP can achieve cross-request effects using tools like Redis, the approaches differ fundamentally Sample Go Code Analysis package main import ( \u0026#34;fmt\u0026#34; \u0026#34;github.com/gin-gonic/gin\u0026#34; \u0026#34;net/http\u0026#34; \u0026#34;time\u0026#34; ) func main() { router := gin.Default() router.GET(\u0026#34;/ping\u0026#34;, func(c *gin.Context) { go func() { var i int for { i++ fmt.Println(i) time.Sleep(time.Second) } }() time.Sleep(time.Second * 5) c.String(http.StatusOK, \u0026#34;pong\u0026#34;) }) router.Run(\u0026#34;:8888\u0026#34;) } Accessing http://127.0.0.1:8888/ping PHP expectation: Console prints 1-5 then returns response Go reality: Numbers keep incrementing indefinitely until server shutdown Solution using Context-aware goroutine: package main import ( \u0026#34;fmt\u0026#34; \u0026#34;github.com/gin-gonic/gin\u0026#34; \u0026#34;net/http\u0026#34; \u0026#34;time\u0026#34; ) func main() { router := gin.Default() router.GET(\u0026#34;/ping\u0026#34;, func(c *gin.Context) { go func() { var i int for { select { case \u0026lt;-c.Request.Context().Done(): return default: i++ fmt.Println(i) time.Sleep(time.Second) } } }() time.Sleep(time.Second * 5) c.String(http.StatusOK, \u0026#34;pong\u0026#34;) }) router.Run(\u0026#34;:8888\u0026#34;) } Key mechanism: Monitoring c.Request.Context().Done() status Goroutine terminates automatically when request completes PHP executes within the request handler\u0026rsquo;s lifecycle Asynchronous operations in PHP require external tools (e.g., Redis queues) Go natively supports controlled concurrency via goroutines and Context Context Parameter Reference Patterns package main import ( \u0026#34;context\u0026#34; \u0026#34;fmt\u0026#34; \u0026#34;github.com/gin-gonic/gin\u0026#34; \u0026#34;github.com/go-redis/redis/v8\u0026#34; \u0026#34;net/http\u0026#34; ) var ctx = context.Background() func main() { // Redis client setup omitted g := gin.Default() g.GET(\u0026#34;/ping\u0026#34;, func(c *gin.Context) { var msg string // Option 1: Global context msg = client.Get(ctx, \u0026#34;ping\u0026#34;).String() // Option 2: Empty context msg = client.Get(context.Background(), \u0026#34;ping\u0026#34;).String() // Option 3: Gin context msg = client.Get(c, \u0026#34;ping\u0026#34;).String() // Option 4: Request context (Correct) msg = client.Get(c.Request.Context(), \u0026#34;ping\u0026#34;).String() c.String(http.StatusOK, msg) }) } Expert Analysis: \u0026gt; 4 is the right choice. 1 is problematic due to using a global context 2 creates a pointless empty context 3 incorrectly uses Gin context instead of context.Context Reference: https://github.com/go-redis/redis/issues/1594\nRecommended Reading https://blog.golang.org/context\n","date":"2021-01-08T14:55:21+08:00","image":"https://sethix.com/posts/2021010814/cover_huce1d1ec607c909c8a636095685740c44_20008_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021010814/","title":"Differences Between Go and PHP and Parameter Passing in Context"},{"content":"Previous API Request Flow User opens APP and requests business API Business API requests recommendation algorithm (with fault tolerance) Recommendation algorithm requests internal service Internal service provides business interface data to recommendation algorithm (e.g., manually configured recommendations) user -\u0026gt; API -\u0026gt; recommend service -\u0026gt; inner service user \u0026lt;- API \u0026lt;- recommend service \u0026lt;- inner service Originally built with Laravel, both API and inner service faced a single-point bottleneck. While API servers could scale horizontally, the inner service remained single-node. This prompted the Go refactoring initiative.\nKey Libraries Used Web Framework: https://github.com/gin-gonic/gin ORM: https://github.com/go-gorm/gorm Cache Middleware: https://github.com/gin-contrib/cache HTTP Testing: https://github.com/gavv/httpexpect Environment Loading: https://github.com/joho/godotenv Environment Parsing: https://github.com/joeshaw/envdecode Hot Reload: https://github.com/cosmtrek/air Performance Comparison: PHP/Laravel vs Go/gin in Inner Service Server Specs: 2-core CPU, 8GB RAM\ntop %Cpu0 %Cpu1 KiB Mem : 7645252 total Without API Caching\n# PHP (port 8888) ab -n 10000 -c 100 127.0.0.1:8888/api/v0/albums Requests per second: 107.49 [#/sec] (mean) # Go (port 9998) ab -n 10000 -c 100 127.0.0.1:9998/api/v1/albums Requests per second: 2719.86 [#/sec] (mean) With Redis Caching\n# PHP (OPcache enabled) ab -n 10000 -c 100 127.0.0.1:8888/api/v0/albums Requests per second: 124.89 [#/sec] (mean) # Go ab -n 10000 -c 100 127.0.0.1:9998/api/v0/albums Requests per second: 4191.87 [#/sec] (mean) ","date":"2021-01-06T13:00:27+08:00","image":"https://sethix.com/posts/2021010613/cover_huc021584384179d99b989c75cbbd9b15e_12745_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2021010613/","title":"Today Completed Refactoring All Internal APIs from PHP to Go"},{"content":"I\u0026rsquo;ve long been curious why MySQL\u0026rsquo;s timestamp type can effortlessly handle time zone issues. In practical use with Laravel frameworks, Migration files default to timestamp fields without requiring special attention.\nGetting Started Check current database time zone settings mysql\u0026gt; show variables like \u0026#34;%time_zone%\u0026#34;; +------------------+--------+ | Variable_name | Value | +------------------+--------+ | system_time_zone | CST | | time_zone | +08:00 | +------------------+--------+ 2 rows in set (0.30 sec) View table structure mysql\u0026gt; desc timestamp_test; +--------------+-----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-----------+------+-----+---------+----------------+ | id | int | NO | PRI | NULL | auto_increment | | created_time | datetime | YES | | NULL | | | created_at | timestamp | YES | | NULL | | +--------------+-----------+------+-----+---------+----------------+ 3 rows in set (0.26 sec) Insert data mysql\u0026gt; insert into timestamp_test(created_time, created_at) values(\u0026#39;2020-12-09 08:00:00\u0026#39;, \u0026#39;2020-12-09 08:00:00\u0026#39;); Query OK, 1 row affected (0.22 sec) mysql\u0026gt; select * from timestamp_test; +----+---------------------+---------------------+ | id | created_time | created_at | +----+---------------------+---------------------+ | 1 | 2020-12-09 08:00:00 | 2020-12-09 08:00:00 | +----+---------------------+---------------------+ 1 row in set (0.06 sec) Test time zone changes\nNow let\u0026rsquo;s modify the time zone and insert data again: mysql\u0026gt; SET time_zone = \u0026#34;+00:00\u0026#34;; Query OK, 0 rows affected (0.03 sec) mysql\u0026gt; insert into timestamp_test(created_time, created_at) values(\u0026#39;2020-12-09 08:00:00\u0026#39;, \u0026#39;2020-12-09 08:00:00\u0026#39;); Query OK, 1 row affected (0.03 sec) mysql\u0026gt; SET time_zone = \u0026#34;+08:00\u0026#34;; Query OK, 0 rows affected (0.04 sec) Observe the results\nBoth inserts used the same SQL, but the created_at values differ by exactly the time zone offset: mysql\u0026gt; select * from timestamp_test; +----+---------------------+---------------------+ | id | created_time | created_at | +----+---------------------+---------------------+ | 1 | 2020-12-09 08:00:00 | 2020-12-09 08:00:00 | | 2 | 2020-12-09 08:00:00 | 2020-12-09 16:00:00 | +----+---------------------+---------------------+ 2 rows in set (0.06 sec) Verify underlying timestamps\nThe stored UNIX timestamps remain constant despite time zone changes: mysql\u0026gt; select *, unix_timestamp(created_at) from timestamp_test; +----+---------------------+---------------------+----------------------------+ | id | created_time | created_at | unix_timestamp(created_at) | +----+---------------------+---------------------+----------------------------+ | 1 | 2020-12-09 08:00:00 | 2020-12-09 08:00:00 | 1607472000 | | 2 | 2020-12-09 08:00:00 | 2020-12-09 16:00:00 | 1607500800 | +----+---------------------+---------------------+----------------------------+ 2 rows in set (0.06 sec) mysql\u0026gt; SET time_zone = \u0026#34;+00:00\u0026#34;; Query OK, 0 rows affected (0.09 sec) mysql\u0026gt; select *, unix_timestamp(created_at) from timestamp_test; +----+---------------------+---------------------+----------------------------+ | id | created_time | created_at | unix_timestamp(created_at) | +----+---------------------+---------------------+----------------------------+ | 1 | 2020-12-09 08:00:00 | 2020-12-09 00:00:00 | 1607472000 | | 2 | 2020-12-09 08:00:00 | 2020-12-09 08:00:00 | 1607500800 | +----+---------------------+---------------------+----------------------------+ 2 rows in set (0.18 sec) The key mechanism: MySQL stores UTC timestamps internally. During writes, it converts local time to UTC using the session time zone. During reads, it converts UTC back to the session\u0026rsquo;s local time zone. All conversions happen transparently.\nPractical example: A record stored as 2020-12-09 08:00:00 in +08:00 time zone When queried in +08:00: remains 2020-12-09 08:00:00 When queried in +00:00: automatically becomes 2020-12-09 00:00:00 This automatic conversion eliminates manual time zone calculations in applications.\n","date":"2020-12-09T17:30:25+08:00","image":"https://sethix.com/posts/2020120917/cover_hucf2d690a15dd9b9bbec5aa5b28b33d75_82736_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2020120917/","title":"Why Timestamp in MySQL Handles Time Zones Automatically"},{"content":" When implementing Chinese search, many developers naturally use the ik tokenizer plugin from GitHub A common mapping configuration following official documentation examples looks like this: { \u0026#34;properties\u0026#34;: { \u0026#34;title\u0026#34;: { \u0026#34;type\u0026#34;: \u0026#34;text\u0026#34;, \u0026#34;analyzer\u0026#34;: \u0026#34;ik_max_word\u0026#34;, \u0026#34;search_analyzer\u0026#34;: \u0026#34;ik_smart\u0026#34; } } } Let\u0026rsquo;s examine data in a test index containing two documents: \u0026ldquo;打火车\u0026rdquo; (beat train) and \u0026ldquo;火车\u0026rdquo; (train) curl 127.0.0.1:9200/test/_search | jq { \u0026#34;took\u0026#34;: 1, \u0026#34;timed_out\u0026#34;: false, \u0026#34;_shards\u0026#34;: { \u0026#34;total\u0026#34;: 1, \u0026#34;successful\u0026#34;: 1, \u0026#34;skipped\u0026#34;: 0, \u0026#34;failed\u0026#34;: 0 }, \u0026#34;hits\u0026#34;: { \u0026#34;total\u0026#34;: { \u0026#34;value\u0026#34;: 2, \u0026#34;relation\u0026#34;: \u0026#34;eq\u0026#34; }, \u0026#34;max_score\u0026#34;: 1, \u0026#34;hits\u0026#34;: [ { \u0026#34;_index\u0026#34;: \u0026#34;test\u0026#34;, \u0026#34;_type\u0026#34;: \u0026#34;_doc\u0026#34;, \u0026#34;_id\u0026#34;: \u0026#34;Video_1\u0026#34;, \u0026#34;_score\u0026#34;: 1, \u0026#34;_source\u0026#34;: { \u0026#34;id\u0026#34;: 1, \u0026#34;title\u0026#34;: \u0026#34;打火车\u0026#34; } }, { \u0026#34;_index\u0026#34;: \u0026#34;test\u0026#34;, \u0026#34;_type\u0026#34;: \u0026#34;_doc\u0026#34;, \u0026#34;_id\u0026#34;: \u0026#34;Video_2\u0026#34;, \u0026#34;_score\u0026#34;: 1, \u0026#34;_source\u0026#34;: { \u0026#34;id\u0026#34;: 2, \u0026#34;title\u0026#34;: \u0026#34;火车\u0026#34; } } ] } } Searching for \u0026ldquo;打火车\u0026rdquo; yields unexpected ranking: curl 127.0.0.1:9200/test/_search?q=打火车 | jq { \u0026#34;took\u0026#34;: 2, \u0026#34;timed_out\u0026#34;: false, \u0026#34;_shards\u0026#34;: { \u0026#34;total\u0026#34;: 1, \u0026#34;successful\u0026#34;: 1, \u0026#34;skipped\u0026#34;: 0, \u0026#34;failed\u0026#34;: 0 }, \u0026#34;hits\u0026#34;: { \u0026#34;total\u0026#34;: { \u0026#34;value\u0026#34;: 2, \u0026#34;relation\u0026#34;: \u0026#34;eq\u0026#34; }, \u0026#34;max_score\u0026#34;: 0.21110919, \u0026#34;hits\u0026#34;: [ { \u0026#34;_index\u0026#34;: \u0026#34;test\u0026#34;, \u0026#34;_type\u0026#34;: \u0026#34;_doc\u0026#34;, \u0026#34;_id\u0026#34;: \u0026#34;Video_2\u0026#34;, \u0026#34;_score\u0026#34;: 0.21110919, \u0026#34;_source\u0026#34;: { \u0026#34;id\u0026#34;: 2, \u0026#34;title\u0026#34;: \u0026#34;火车\u0026#34; } }, { \u0026#34;_index\u0026#34;: \u0026#34;test\u0026#34;, \u0026#34;_type\u0026#34;: \u0026#34;_doc\u0026#34;, \u0026#34;_id\u0026#34;: \u0026#34;Video_1\u0026#34;, \u0026#34;_score\u0026#34;: 0.160443, \u0026#34;_source\u0026#34;: { \u0026#34;id\u0026#34;: 1, \u0026#34;title\u0026#34;: \u0026#34;打火车\u0026#34; } } ] } } Surprisingly, the document containing \u0026ldquo;火车\u0026rdquo; scores higher than \u0026ldquo;打火车\u0026rdquo; Using the elasticsearch-head plugin for analysis reveals the tokenization difference: curl 127.0.0.1:9200/test/_doc/Video_1/_termvectors?fields=title | jq { \u0026#34;_index\u0026#34;: \u0026#34;test\u0026#34;, \u0026#34;_type\u0026#34;: \u0026#34;_doc\u0026#34;, \u0026#34;_id\u0026#34;: \u0026#34;Video_1\u0026#34;, \u0026#34;_version\u0026#34;: 1, \u0026#34;found\u0026#34;: true, \u0026#34;took\u0026#34;: 0, \u0026#34;term_vectors\u0026#34;: { \u0026#34;title\u0026#34;: { \u0026#34;field_statistics\u0026#34;: { \u0026#34;sum_doc_freq\u0026#34;: 3, \u0026#34;doc_count\u0026#34;: 2, \u0026#34;sum_ttf\u0026#34;: 3 }, \u0026#34;terms\u0026#34;: { \u0026#34;打火\u0026#34;: { \u0026#34;term_freq\u0026#34;: 1, \u0026#34;tokens\u0026#34;: [ { \u0026#34;position\u0026#34;: 0, \u0026#34;start_offset\u0026#34;: 0, \u0026#34;end_offset\u0026#34;: 2 } ] }, \u0026#34;火车\u0026#34;: { \u0026#34;term_freq\u0026#34;: 1, \u0026#34;tokens\u0026#34;: [ { \u0026#34;position\u0026#34;: 1, \u0026#34;start_offset\u0026#34;: 1, \u0026#34;end_offset\u0026#34;: 3 } ] } } } } } The term \u0026ldquo;打火车\u0026rdquo; is split into \u0026ldquo;打火\u0026rdquo; (flame) and \u0026ldquo;火车\u0026rdquo; (train), causing scoring anomalies Solution: Use consistent tokenizers for both indexing and searching { \u0026#34;properties\u0026#34;: { \u0026#34;title\u0026#34;: { \u0026#34;type\u0026#34;: \u0026#34;text\u0026#34;, \u0026#34;analyzer\u0026#34;: \u0026#34;ik_smart\u0026#34;, \u0026#34;search_analyzer\u0026#34;: \u0026#34;ik_smart\u0026#34; } } } Verified tokenization after modification: curl 127.0.0.1:9200/test/_doc/Video_1/_termvectors?fields=title | jq { \u0026#34;_index\u0026#34;: \u0026#34;test\u0026#34;, \u0026#34;_type\u0026#34;: \u0026#34;_doc\u0026#34;, \u0026#34;_id\u0026#34;: \u0026#34;Video_1\u0026#34;, \u0026#34;_version\u0026#34;: 1, \u0026#34;found\u0026#34;: true, \u0026#34;took\u0026#34;: 0, \u0026#34;term_vectors\u0026#34;: { \u0026#34;title\u0026#34;: { \u0026#34;field_statistics\u0026#34;: { \u0026#34;sum_doc_freq\u0026#34;: 3, \u0026#34;doc_count\u0026#34;: 2, \u0026#34;sum_ttf\u0026#34;: 3 }, \u0026#34;terms\u0026#34;: { \u0026#34;打\u0026#34;: { \u0026#34;term_freq\u0026#34;: 1, \u0026#34;tokens\u0026#34;: [ { \u0026#34;position\u0026#34;: 0, \u0026#34;start_offset\u0026#34;: 0, \u0026#34;end_offset\u0026#34;: 1 } ] }, \u0026#34;火车\u0026#34;: { \u0026#34;term_freq\u0026#34;: 1, \u0026#34;tokens\u0026#34;: [ { \u0026#34;position\u0026#34;: 1, \u0026#34;start_offset\u0026#34;: 1, \u0026#34;end_offset\u0026#34;: 3 } ] } } } } } Final search results show correct ranking: curl 127.0.0.1:9200/test/_search?q=打火车 | jq { \u0026#34;took\u0026#34;: 1, \u0026#34;timed_out\u0026#34;: false, \u0026#34;_shards\u0026#34;: { \u0026#34;total\u0026#34;: 1, \u0026#34;successful\u0026#34;: 1, \u0026#34;skipped\u0026#34;: 0, \u0026#34;failed\u0026#34;: 0 }, \u0026#34;hits\u0026#34;: { \u0026#34;total\u0026#34;: { \u0026#34;value\u0026#34;: 2, \u0026#34;relation\u0026#34;: \u0026#34;eq\u0026#34; }, \u0026#34;max_score\u0026#34;: 0.77041256, \u0026#34;hits\u0026#34;: [ { \u0026#34;_index\u0026#34;: \u0026#34;test\u0026#34;, \u0026#34;_type\u0026#34;: \u0026#34;_doc\u0026#34;, \u0026#34;_id\u0026#34;: \u0026#34;Video_1\u0026#34;, \u0026#34;_score\u0026#34;: 0.77041256, \u0026#34;_source\u0026#34;: { \u0026#34;id\u0026#34;: 1, \u0026#34;title\u0026#34;: \u0026#34;打火车\u0026#34; } }, { \u0026#34;_index\u0026#34;: \u0026#34;test\u0026#34;, \u0026#34;_type\u0026#34;: \u0026#34;_doc\u0026#34;, \u0026#34;_id\u0026#34;: \u0026#34;Video_2\u0026#34;, \u0026#34;_score\u0026#34;: 0.21110919, \u0026#34;_source\u0026#34;: { \u0026#34;id\u0026#34;: 2, \u0026#34;title\u0026#34;: \u0026#34;火车\u0026#34; } } ] } } ","date":"2020-11-30T22:51:55+08:00","image":"https://sethix.com/posts/2020113022/cover_hu4ab6886050842d6cc7588c7f314fb7e7_15478_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2020113022/","title":"Elasticsearch Search Ranking Issues Caused by Different Tokenizers"},{"content":" Maintaining consistent code style is crucial in team development Configure PSR12 style in PHPStorm File -\u0026gt; Settings -\u0026gt; Editor-\u0026gt; Code Style -\u0026gt; Set from -\u0026gt; select PSR12 PhpStorm PSR12 Code Style Settings Using PHP_CodeSniffer for Code Style Checks Create phpcs.xml in project root for team-wide usage\nConfiguration notes:\nOfficial documentation is limited - often requires debugging error messages Example: To disable end xxx() comments: Search source code for //end Locate PHP_CodeSniffer\\Standards\\Squiz\\Sniffs\\Commenting::ClosingDeclarationCommentSniff Remove \u0026lt;rule ref=\u0026quot;Squiz.Commenting.ClosingDeclarationComment\u0026quot;/\u0026gt; from config Static Analysis with phpstan Create phpstan.neon configuration in project root Workflow Implementation Team members work on feature branches Merge to dev branch triggers git hook Stage server performs: PHPUnit tests PHPCS style checks (with phpcbf auto-fix) PHPStan static analysis Successful checks trigger merge to master; failures trigger notifications Configuration Notes For containerized testing: Share host machine\u0026rsquo;s SSH credentials: volumes: # Share Git credentials - /root/.ssh:/home/laradock/.ssh Ensure proper permissions for SSH directory access ","date":"2020-11-02T15:32:57+08:00","image":"https://sethix.com/posts/2020110215/cover_huf981fd0d0dc70e29f5ad92e06e2543f6_30475_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2020110215/","title":"Code Style and Quality Control in PHP Projects"},{"content":"PHP has always operated with a page-level lifecycle, where variables from previous requests aren\u0026rsquo;t shared with subsequent ones (unlike resident memory languages).\nMost PHP code executes sequentially from top to bottom without callback capabilities The curl_multi_* function family enables \u0026ldquo;multi-threaded\u0026rdquo;-like behavior in PHP Recommended library for easier implementation: https://github.com/php-curl-class/php-curl-class Official concurrent request demo\n\u0026lt;?php require __DIR__ . \u0026#39;/../vendor/autoload.php\u0026#39;; use Curl\\MultiCurl; $urls = array( \u0026#39;tag3\u0026#39; =\u0026gt; \u0026#39;https://httpbin.org/post\u0026#39;, \u0026#39;tag4\u0026#39; =\u0026gt; \u0026#39;https://httpbin.org/get\u0026#39;, \u0026#39;tag5\u0026#39; =\u0026gt; \u0026#39;https://httpbin.org/html\u0026#39;, ); $multi_curl = new MultiCurl(); $data = []; $multi_curl-\u0026gt;success(function ($instance) { echo \u0026#39;Call to \u0026#39; . $instance-\u0026gt;id . \u0026#39; with \u0026#34;\u0026#39; . $instance-\u0026gt;myTag . \u0026#39;\u0026#34; succeeded.\u0026#39; . \u0026#34;\\n\u0026#34;; }); $multi_curl-\u0026gt;error(function ($instance) { echo \u0026#39;Call to \u0026#39; . $instance-\u0026gt;id . \u0026#39; with \u0026#34;\u0026#39; . $instance-\u0026gt;myTag . \u0026#39;\u0026#34; failed.\u0026#39; . \u0026#34;\\n\u0026#34;; }); $multi_curl-\u0026gt;complete(function ($instance) use (\u0026amp;$data) { echo \u0026#39;Call to \u0026#39; . $instance-\u0026gt;id . \u0026#39; with \u0026#34;\u0026#39; . $instance-\u0026gt;myTag . \u0026#39;\u0026#34; completed.\u0026#39; . \u0026#34;\\n\u0026#34;; $data[] = $instance-\u0026gt;tag; }); foreach ($urls as $tag =\u0026gt; $url) { $instance = $multi_curl-\u0026gt;addGet($url); $instance-\u0026gt;myTag = $tag; } // Wait for all requests to complete $multi_curl-\u0026gt;start(); // Tag order isn\u0026#39;t guaranteed, depends on HTTP response speed var_dump($data); ","date":"2020-06-17T15:04:16+08:00","image":"https://sethix.com/posts/2020061715/cover_hu9f6b9a7a39e5b13964deedeaeb636472_9783_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2020061715/","title":"Making Concurrent Requests in PHP"},{"content":"Bucket Sort is well-suited for sorting numbers in the range of 0~100, but its efficiency decreases when dealing with data that has a wide value range.\nAlgorithm Steps Create n empty buckets based on requirements Traverse the input array to find the maximum and minimum values For each element num, calculate bucket index using formula: floor((num - min) / n) If a bucket already contains elements, maintain elements in sorted order (using linked list) Repeat steps 3-4 until all elements are distributed Concatenate all buckets\u0026rsquo; linked lists and output the sorted array package main import ( \u0026#34;fmt\u0026#34; \u0026#34;math\u0026#34; ) func main() { data := []int{111, 9, 2, 4, 9, 3, 3, 5, 7, 1, 8, 2, 11, 22, 99, 192} fmt.Println(BucketSort(data, 4)) } func BucketSort(data []int, buckets int) []int { if len(data) == 0 { return data } // Find min and max values min, max := data[0], data[0] for _, num := range data { if num \u0026lt; min { min = num } if num \u0026gt; max { max = num } } bucketChunk := (max - min + 1) / buckets bucketLinks := make([]*LinkList, buckets) // Distribute numbers into buckets for _, num := range data { // Find target bucket bucketIndex := int(math.Floor(float64((num - min) / bucketChunk))) if bucketLinks[bucketIndex] == nil { bucketLinks[bucketIndex] = \u0026amp;LinkList{} } bucketLinks[bucketIndex].insertSorted(num) } // Merge all buckets index := 0 sortedData := make([]int, len(data)) for _, bucket := range bucketLinks { if bucket == nil { continue } current := bucket.head for current != nil { sortedData[index] = current.data index++ current = current.next } } return sortedData } type LinkList struct { head *Node } type Node struct { data int next *Node } func (ll *LinkList) insertSorted(num int) { if ll.head == nil || ll.head.data \u0026gt; num { ll.head = \u0026amp;Node{num, ll.head} return } current := ll.head for current.next != nil \u0026amp;\u0026amp; current.next.data \u0026lt;= num { current = current.next } current.next = \u0026amp;Node{num, current.next} } ","date":"2020-06-07T09:28:23+08:00","image":"https://sethix.com/posts/2020060709/cover_hucc41ec09e9a913a33a1b1177a13b3587_8592_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2020060709/","title":"Sorting Algorithm - Bucket Sort"},{"content":" Many introductory articles are available online. I found these three particularly beginner-friendly:\nDocker Tutorial Series from Basics to Advanced\nDocker Tutorial Series (2): Docker Build\nDocker Tutorial Series (3): Docker-Compose Docker You can directly pull an image using the command (take nginx as an example): docker pull nginx Dockerfile Essentially a text file describing how an image is built. After writing a Dockerfile, execute docker build to construct the image based on the instructions. Built images can be pushed to repositories, with Docker Hub being the most commonly used official repository. Docker Compose Docker prefers splitting services into separate containers for easier management and partial rebuilding when environments change (compared to bundling everything in a single container). First Steps Run docker pull php-fpm, then execute commands like apt and docker-php-ext-enable directly in the container. Note: The php-fpm image is built on Ubuntu. Check its Dockerfile to see available commands. LaraDock Pitfalls and Solutions The php-worker container cannot write logs directly to the project. Consider using Redis instead. Configuring Supervisor in laradock with php-worker\nThe php-worker container doesn\u0026rsquo;t have bash access (unlike other containers). Supervisord automatically keeps processes alive based on configurations when the php-worker container starts. After modifying supervisord configurations, rebuild the container: docker-compose build php-worker \u0026amp;\u0026amp; docker-compose up -d php-worker If using Redis as the queue driver, install it in the php-worker container by setting .env: PHP_WORKER_INSTALL_REDIS=true ","date":"2020-06-03T11:40:39+08:00","image":"https://sethix.com/posts/2020060311/cover_hude649f97d827a9b65ff06c4b8c11b2f9_24857_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2020060311/","title":"Getting Started with Docker and Docker-Compose"},{"content":"Recently, the user logs in our project have reached hundreds of millions. For convenience, we previously stored them directly in MySQL. Now big data requirements are pushing us to migrate these logs to Kafka.\nInstallation Development Environment Considerations Windows for local development Non-compiled installation for testing environment Production environment maintained by Ops team Linux Installation Ensure pecl is installed: pecl help version Install via pecl: sudo pecl install rdkafka Compile from Source Install dependencies (requires librdkafka):\nwget -c https://github.com/edenhill/librdkafka/archive/v0.11.0.tar.gz tar xvzf v0.11.0.tar.gz cd librdkafka-0.11.0/ ./configure make sudo make install Install php-rdkafka extension:\nwget -c https://github.com/arnaud-lb/php-rdkafka/archive/3.0.4.tar.gz tar xvzf 3.0.4.tar.gz cd php-rdkafka-3.0.4 /usr/bin/phpize ./configure --with-php-config=/www/server/php/71/bin/php-config --with-rdkafka make all -j 5 sudo make install Add to php.ini:\nextension = rdkafka.so Reference: PHP Kafka Extension Installation\nWindows Installation Download precompiled DLLs matching your PHP version (NTS/TS, x86/x64) from:\nhttps://windows.php.net/downloads/pecl/releases/rdkafka/\nPlace files:\nlibrdkafka.dll → PHP root directory php_rdkafka.dll → PHP ext directory Add to php.ini:\nextension=php_rdkafka.dll Verify installation:\nphp -m | findstr rdkafka Check Extension Version php --ri rdkafka /* Output: rdkafka rdkafka support =\u0026gt; enabled version =\u0026gt; 3.0.1 librdkafka version (runtime) =\u0026gt; 0.9.4 librdkafka version (build) =\u0026gt; 0.9.4.0 */ Basic Usage Producer Example // producer.php $configBrokers = \u0026#39;127.0.0.1:9092\u0026#39;; $configTopic = \u0026#39;test\u0026#39;; $conf = new \\RdKafka\\Conf(); $conf-\u0026gt;setDrMsgCb(function ($kafka, $message) { var_dump(\u0026#39;Message delivered:\u0026#39;, $message); }); $conf-\u0026gt;setErrorCb(function ($kafka, $err, $reason) { echo \u0026#34;Error: $err ($reason)\\n\u0026#34;; }); $producer = new \\RdKafka\\Producer($conf); $producer-\u0026gt;addBrokers($configBrokers); $topic = $producer-\u0026gt;newTopic($configTopic); for ($i = 0; $i \u0026lt; 100; $i++) { $topic-\u0026gt;produce(RD_KAFKA_PARTITION_UA, 0, \u0026#34;Log entry: $i\u0026#34;); } // Flush messages while ($producer-\u0026gt;getOutQLen() \u0026gt; 0) { $producer-\u0026gt;poll(1); } Consumer Example // consumer.php $configBrokers = \u0026#39;127.0.0.1:9092\u0026#39;; $configTopic = \u0026#39;test\u0026#39;; $consumer = new \\RdKafka\\Consumer(); $consumer-\u0026gt;addBrokers($configBrokers); $topic = $consumer-\u0026gt;newTopic($configTopic); $topic-\u0026gt;consumeStart(0, RD_KAFKA_OFFSET_END); while (true) { $message = $topic-\u0026gt;consume(0, 1000); switch ($message-\u0026gt;err) { case RD_KAFKA_RESP_ERR_NO_ERROR: echo \u0026#34;Received: {$message-\u0026gt;payload}\\n\u0026#34;; break; case RD_KAFKA_RESP_ERR__PARTITION_EOF: echo \u0026#34;No more messages\\n\u0026#34;; break; case RD_KAFKA_RESP_ERR__TIMED_OUT: echo \u0026#34;Timeout\\n\u0026#34;; break; default: echo \u0026#34;Error: {$message-\u0026gt;err}\\n\u0026#34;; break; } } Key Notes:\nProducers work asynchronously - use poll() to ensure message delivery Consumers can start from RD_KAFKA_OFFSET_END to read new messages only Always handle consumer timeouts and partition EOF conditions ","date":"2020-05-08T15:54:20+08:00","image":"https://sethix.com/posts/2020050815/cover_hu9d53b7c5db90a59ed4016e0c5da31bd0_5223_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2020050815/","title":"Install php-rdkafka Extension and Use Kafka for Logging"},{"content":"A recent project required enhancements to existing search functionality:\nElasticsearch 7.6 (Note: parameters may vary across major versions) Original search: Simple full-text indexing of title + body content\nNew requirements: Improve result sorting based on multiple factors - publication date (older content should score lower), manually assigned weight values (higher is better), and popularity metrics.\nAfter researching the documentation, we found Elasticsearch natively supports this through Decay Functions.\nElasticsearch\u0026rsquo;s built-in decay functions work with numeric, date, and geo fields. You can define an ideal value (origin), and scores will decrease as values deviate from this ideal.\nSupported parameters:\norigin: The ideal value that receives full score (1.0) offset: Values within ±offset range from origin also get full score scale: Determines decay rate outside the offset range decay: Acceptable score at edge of scaling range (default 0.5) Decay Function Patterns linear: Linear decay (scores drop to 0 beyond range) exp: Rapid initial decay slowing over time gauss: Bell-curve style decay (slow-fast-slow) Our configuration example:\n{ \u0026#34;query\u0026#34;: { // Using function scoring \u0026#34;function_score\u0026#34;: { // Core search query \u0026#34;query\u0026#34;: { \u0026#34;multi_match\u0026#34;: { \u0026#34;query\u0026#34;: \u0026#34;blog\u0026#34;, \u0026#34;fields\u0026#34;: [ \u0026#34;title^10\u0026#34;, // Title has 10x weight of body \u0026#34;body\u0026#34; ] } }, // Multiply function score with original score \u0026#34;boost_mode\u0026#34;: \u0026#34;multiply\u0026#34;, // Sum scores from multiple functions \u0026#34;score_mode\u0026#34;: \u0026#34;sum\u0026#34;, \u0026#34;functions\u0026#34;: [ // Gaussian decay for date field (2020-04-27 as ideal) // Full score within 30 days, gauss decay from 30-90 days // Minimum score (0.5) beyond 90 days { \u0026#34;gauss\u0026#34;: { \u0026#34;created_date\u0026#34;: { \u0026#34;origin\u0026#34;: \u0026#34;2020-04-27\u0026#34;, \u0026#34;offset\u0026#34;: \u0026#34;30d\u0026#34;, \u0026#34;scale\u0026#34;: \u0026#34;60d\u0026#34;, \u0026#34;decay\u0026#34;: 0.5 } }, \u0026#34;weight\u0026#34;: 1 }, // Linear decay for popularity score // Full score for 90-110 values, linear decay to 0.5 at 160 { \u0026#34;linear\u0026#34;: { \u0026#34;hot_value\u0026#34;: { \u0026#34;origin\u0026#34;: 100, \u0026#34;offset\u0026#34;: 10, \u0026#34;scale\u0026#34;: 50, \u0026#34;decay\u0026#34;: 0.5 } }, \u0026#34;weight\u0026#34;: 2 // Double influence of this function } ] } } } References:\nElasticsearch Function Score Query Documentation\nZhihu Live: Full-Text Search with Elasticsearch\n","date":"2020-04-27T18:18:12+08:00","image":"https://sethix.com/posts/2020042718/cover_huab9d071dc8e316165916088c5e3ba51c_14964_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2020042718/","title":"Using Decay Functions in ElasticSearch to Perfect Your Search Results"},{"content":"Background Recently encountered a problem during code refactoring: needing to batch download and package a set of images from OSS The old server directly mounted OSS to the filesystem, using Linux commands for copying and packaging (fast but incompatible with the new server architecture) OSS doesn\u0026rsquo;t provide direct packaging APIs (Qiniu Cloud supports this) Solutions Considered Discarded PHP backend fetching images to memory for packaging (memory overload risk with AI/PSD files) Discarded PHP backend saving images to disk for packaging (slow fetching and processing for large files) Implemented Frontend solution: JS fetches file info from backend, asynchronously downloads resources, and packages them client-side Prerequisites CORS configuration: Requires adding cross-origin headers on OSS/resource server CDN bypass: Configure a dedicated domain without CDN acceleration (skip if not using CDN) Implementation Steps Use JSZip library for client-side zip operations Utilize JSZip-utils for handling remote resource fetching Core implementation logic: \u0026lt;!-- Include required libraries --\u0026gt; \u0026lt;script type=\u0026#34;text/javascript\u0026#34; src=\u0026#34;/xxx/jszip.min.js\u0026#34;\u0026gt;\u0026lt;/script\u0026gt; \u0026lt;script type=\u0026#34;text/javascript\u0026#34; src=\u0026#34;/xxx/jszip-utils.min.js\u0026#34;\u0026gt;\u0026lt;/script\u0026gt; \u0026lt;!--[if IE]\u0026gt; \u0026lt;script type=\u0026#34;text/javascript\u0026#34; src=\u0026#34;/xxx/jszip-utils-ie.min.js\u0026#34;\u0026gt;\u0026lt;/script\u0026gt; \u0026lt;![endif]--\u0026gt; \u0026lt;script\u0026gt; let total = 0; let progress = 0; // Triggered by button click or other event $.get(\u0026#39;/urls\u0026#39;, function(res) { // Sample response data structure: // {url: \u0026#39;x.jpg\u0026#39;, filename: \u0026#39;xx.jpg\u0026#39;, path: \u0026#39;xxxx\u0026#39;} total = res.data.length; if (total === 0) { console.error(\u0026#39;No images available for download in the gallery\u0026#39;); return; } let zip = new JSZip(); let folderMap = {}; res.data.forEach(function(data) { JSZipUtils.getBinaryContent( data.url, function(err, binData) { progress++; if (err \u0026amp;\u0026amp; progress \u0026lt; total) { console.log(err); return; } if (!folderMap[data.path]) { folderMap[data.path] = zip.folder(data.path); } let currentFolder = folderMap[data.path]; currentFolder.file(data.filename, binData, {binary: true}); if (progress === total) { console.log(\u0026#39;Packaging data, please wait...\u0026#39;); zip.generateAsync({type: \u0026#34;blob\u0026#34;}).then(function(content) { // Trigger file download const link = document.createElement(\u0026#39;a\u0026#39;); link.href = URL.createObjectURL(content); link.download = \u0026#39;archive.zip\u0026#39;; document.body.appendChild(link); link.click(); document.body.removeChild(link); }); } } ); }); }); \u0026lt;/script\u0026gt; Result The implemented solution demonstrates better performance than backend-based approaches by leveraging concurrent downloads and client-side processing. Key advantages:\nNo server-side resource consumption Parallel downloading improves efficiency Native browser compression optimizes memory usage ","date":"2020-04-23T18:56:21+08:00","image":"https://sethix.com/posts/2020042318/cover_hue33d6fafbafc8b6984169542d3762478_1665_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2020042318/","title":"Method for Batch Downloading and Packaging Files from Remote URLs"},{"content":"Given the following string:\nlet str = \u0026#39;为中华\\n\\n只崛aaa起\\n而读书\\n 我是123中国1111人\u0026#39;; Desired Formatting Effects Auto-indent with 4 spaces after each line break Add spacing between numbers and other characters Add spacing between letters and other characters Idempotent formatting (repeated formatting won\u0026rsquo;t cause inconsistencies) Implementation code:\n// Lookahead assertion to ensure no 4 spaces follow const brReg = /\\n(?!\\s{4})/g; // Lookbehind assertion to check preceding characters const numPreReg = /(?\u0026lt;!\\s|\\d)(\\d+)/g; const numExtReg = /(\\d+)(?!\\s|\\d)/g; const charPreReg = /(?\u0026lt;!\\s|[a-zA-Z])([a-zA-Z]+)/g; const charExtReg = /([a-zA-Z]+)(?!\\s|[a-zA-Z])/g; str = str.replace(brReg, \u0026#39;\\n \u0026#39;); str = str.replace(charPreReg, \u0026#39; $1\u0026#39;); str = str.replace(charExtReg, \u0026#39;$1 \u0026#39;); str = str.replace(numPreReg, \u0026#39; $1\u0026#39;); str = str.replace(numExtReg, \u0026#39;$1 \u0026#39;); // Output: 为中华\\n \\n 只崛 aaa 起\\n 而读书\\n 我是 123 中国 1111 人 console.log(JSON.stringify(str)); PS: This formatting logic powers YouMengJi's automatic text formatting feature\n","date":"2020-01-19T14:52:43+08:00","image":"https://sethix.com/posts/2020011914/cover_hu27efcf86d1a794185c99c9470add8e7b_2860_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2020011914/","title":"Using Lookahead and Lookbehind Assertions in Regular Expressions to Format Your Text"},{"content":" When needing HTTP testing in code, Laravel has built-in functionality for this. With Slim, we have to build our own solution. After searching online for examples and finding limited resources, I decided to examine Laravel\u0026rsquo;s source code for inspiration. Discovered that the core idea is to mock a Request object and execute it to get response results. Implemented this approach in Slim framework accordingly. Setting Up Test Files Add autoload configuration in composer.json and run composer dump-auto: \u0026#34;autoload-dev\u0026#34;: { \u0026#34;psr-4\u0026#34;: { \u0026#34;Tests\\\\\u0026#34;: \u0026#34;tests/\u0026#34; } } Create phpunit.xml at root directory: \u0026lt;phpunit bootstrap=\u0026#34;tests/bootstrap.php\u0026#34;\u0026gt; \u0026lt;testsuites\u0026gt; \u0026lt;testsuite name=\u0026#34;Feature\u0026#34;\u0026gt; \u0026lt;directory suffix=\u0026#34;Test.php\u0026#34;\u0026gt;tests\u0026lt;/directory\u0026gt; \u0026lt;/testsuite\u0026gt; \u0026lt;/testsuites\u0026gt; \u0026lt;/phpunit\u0026gt; Create tests/bootstrap.php with content: \u0026lt;?php use Psr\\Http\\Message\\ResponseInterface as Response; use Psr\\Http\\Message\\ServerRequestInterface as Request; use Slim\\Factory\\AppFactory; require __DIR__ . \u0026#39;/../vendor/autoload.php\u0026#39;; $app = AppFactory::create(); $app-\u0026gt;get(\u0026#39;/hello/{name}\u0026#39;, function (Request $request, Response $response, array $args) { $name = $args[\u0026#39;name\u0026#39;]; $response-\u0026gt;getBody()-\u0026gt;write(\u0026#34;Hello, $name\u0026#34;); return $response; }); $app-\u0026gt;get(\u0026#39;/api/v1/users\u0026#39;, function (Request $request, Response $response) { $data = [[\u0026#39;name\u0026#39; =\u0026gt; \u0026#39;Bob\u0026#39;, \u0026#39;age\u0026#39; =\u0026gt; 40]]; $payload = json_encode($data); $response-\u0026gt;getBody()-\u0026gt;write($payload); return $response -\u0026gt;withHeader(\u0026#39;Content-Type\u0026#39;, \u0026#39;application/json\u0026#39;); }); // Do not run the app here // $app-\u0026gt;run(); function getApplication() { global $app; return $app; } Create test file tests/HomeTest.php: \u0026lt;?php namespace Tests; use Nyholm\\Psr7\\Uri; use PHPUnit\\Framework\\TestCase; use Slim\\Factory\\ServerRequestCreatorFactory; class HomeTest extends TestCase { public function testHello() { $name = \u0026#39;Bob\u0026#39;; $serverRequestCreator = ServerRequestCreatorFactory::create(); $request = $serverRequestCreator-\u0026gt;createServerRequestFromGlobals(); $uri = new Uri(); $request = $request-\u0026gt;withUri($uri-\u0026gt;withPath(\u0026#34;/hello/{$name}\u0026#34;)); $response = getApplication()-\u0026gt;handle($request); $responseContent = (string)$response-\u0026gt;getBody(); $this-\u0026gt;assertEquals(\u0026#34;Hello, {$name}\u0026#34;, $responseContent); } public function testJsonApi() { $serverRequestCreator = ServerRequestCreatorFactory::create(); $request = $serverRequestCreator-\u0026gt;createServerRequestFromGlobals(); // Uri and Request objects are immutable - create new instances $uri = new Uri(); $request = $request-\u0026gt;withUri($uri-\u0026gt;withPath(\u0026#39;api/v1/users\u0026#39;)); // For fake query parameters: // $request = $request-\u0026gt;withQueryParams([]); $response = getApplication()-\u0026gt;handle($request); $responseContent = (string)$response-\u0026gt;getBody(); $this-\u0026gt;assertJson($responseContent); } } Finally, execute tests with PHPUnit: $ phpunit PHPUnit 7.5.17 by Sebastian Bergmann and contributors. .. 2 / 2 (100%) Time: 45 ms, Memory: 4.00 MB OK (2 tests, 2 assertions) ","date":"2019-12-04T17:21:20+08:00","image":"https://sethix.com/posts/2019120417/cover_hu5234e78615a6118ed118f24d1fe84119_6950_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2019120417/","title":"Fake Requests in Slim for Your HTTP Testing Needs"},{"content":"When developing web pages or API interfaces, we often encounter the following scenario:\nA request is processed by querying the database and returning transformed data Some pages/interfaces with infrequent data changes (e.g. homepage) may experience performance issues under high traffic Solution: Cache processed content in storage like Redis before returning the response Subsequent requests first check the cache - return immediately if valid If cache expires, repeat steps [3-4] Here\u0026rsquo;s an implementation in Slim4 framework:\n\u0026lt;?php namespace App\\Middleware; use Nyholm\\Psr7\\Stream; use Psr\\Http\\Message\\ResponseInterface; use Psr\\Http\\Message\\ServerRequestInterface; use Psr\\Http\\Server\\RequestHandlerInterface; class PageCacheMiddleware { public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $cachedRoutes = [ \u0026#39;/\u0026#39; =\u0026gt; [], \u0026#39;/categories\u0026#39; =\u0026gt; [], \u0026#39;/articles\u0026#39; =\u0026gt; [], ]; $requestPath = $request-\u0026gt;getUri()-\u0026gt;getPath(); // Bypass non-GET requests and uncached routes if ( (strtoupper($request-\u0026gt;getMethod()) !== \u0026#39;GET\u0026#39;) || !array_key_exists($requestPath, $cachedRoutes) ) { return $handler-\u0026gt;handle($request); } // Generate cache key considering query parameters $requestParameters = $request-\u0026gt;getQueryParams(); $cacheKey = base64_encode($requestPath . json_encode($requestParameters)); // Simulating cache storage with file system (replace with Redis in production) if (file_exists($cacheKey)) { list($cachedResponse, $cachedBody) = unserialize(file_get_contents($cacheKey)); if ($cachedResponse instanceof ResponseInterface) { return $cachedResponse-\u0026gt;withBody(Stream::create($cachedBody)); } } // Process request and cache response $response = $handler-\u0026gt;handle($request); file_put_contents( $cacheKey, serialize([$response, (string)$response-\u0026gt;getBody()]) ); return $response; } } Key implementation details:\nOnly cache specified GET routes Cache key includes URL path and query parameters Serializes both response object and body content File-based caching for demonstration (replace with Redis/Memcached in production) This middleware checks the cache before processing requests and stores responses after initial processing, effectively reducing database queries and computational overhead for cached endpoints.\n","date":"2019-11-28T12:39:39+08:00","image":"https://sethix.com/posts/2019112812/cover_hue50b5fe785895ac0c2fbb6bc6be321fb_27440_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2019112812/","title":"Using Middleware for Request Caching in Slim4"},{"content":"Test Environment Local Configuration (Win 10 i7-8565U 16G)(Nginx 1.15.11)(MySQL 5.5.62) Cloud Server (1 Core 2G)(Nginx 1.16.1)(MySQL 5.5.62) Performance Results Software Database Model Local QPS Cloud Server QPS Laravel 6.3.0 (with session) ORM 12.11 5.15 Laravel 6.3.0 (with session) PDO 13.85 5.31 Laravel 6.3.0 ORM 13.06 5.69 Laravel 6.3.0 PDO 13.98 5.89 Slim 4.3.0 PDO 41.04 43.65 PHP 7.1.9 Native PDO 52.85 51.81 Notes All tests performed using ApacheBench (ab) with command:\nab -n 1000 -c 100 [test_url] ORM vs PDO comparison shows raw database driver performance differences Session handling significantly impacts Laravel\u0026rsquo;s performance Slim framework demonstrates ~3x performance advantage over Laravel in these tests Native PHP implementation achieves the highest QPS as expected ","date":"2019-11-25T15:32:13+08:00","image":"https://sethix.com/posts/2019112515/cover_hu5234e78615a6118ed118f24d1fe84119_6950_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2019112515/","title":"Slim - PHP - Laravel Performance Test"},{"content":"Recently I\u0026rsquo;ve developed several e-commerce projects, which inevitably involved designing coupon systems.\nSince the Monday Mall project didn\u0026rsquo;t have this module, I decided to implement it during this period.\nReferencing JD.com\u0026rsquo;s style, created a template like this:\nCoupon Here\u0026rsquo;s the core logic:\nFirst, we need a coupon template table Stores coupon templates for backend generation and user redemption Requires a separate user coupon table Table structure overview:\nCoupon # Template Table `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT \u0026#39;Coupon title\u0026#39;, `amount` decimal(8,2) NOT NULL COMMENT \u0026#39;Discount amount\u0026#39;, `full_amount` decimal(8,2) NOT NULL COMMENT \u0026#39;Minimum purchase amount\u0026#39;, `score` int(10) unsigned NOT NULL DEFAULT \u0026#39;0\u0026#39; COMMENT \u0026#39;Redemption points required\u0026#39;, `start_date` date NOT NULL COMMENT \u0026#39;Start date\u0026#39;, `end_date` date NOT NULL COMMENT \u0026#39;Expiry date\u0026#39;, `created_at` timestamp NULL DEFAULT NULL COMMENT \u0026#39;Creation time\u0026#39;, `updated_at` timestamp NULL DEFAULT NULL COMMENT \u0026#39;Update time\u0026#39;, # User Coupon Table `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned COMMENT \u0026#39;User ID\u0026#39;, `title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT \u0026#39;Coupon title\u0026#39;, `amount` decimal(8,2) NOT NULL COMMENT \u0026#39;Discount amount\u0026#39;, `full_amount` decimal(8,2) NOT NULL COMMENT \u0026#39;Minimum purchase amount\u0026#39;, `start_date` date NOT NULL COMMENT \u0026#39;Start date\u0026#39;, `end_date` date NOT NULL COMMENT \u0026#39;Expiry date\u0026#39;, `used_at` timestamp NULL DEFAULT NULL COMMENT \u0026#39;Usage time\u0026#39;, `created_at` timestamp NULL DEFAULT NULL COMMENT \u0026#39;Creation time\u0026#39;, `updated_at` timestamp NULL DEFAULT NULL COMMENT \u0026#39;Update time\u0026#39;, Key workflow:\nOperations team creates coupon templates Configure title, discount amount (set full_amount=0 for no minimum purchase) Set points requirement and validity period Users claim coupons in activity center Verify user points if required Copy template fields to user coupon table Apply single-coupon-type restriction if needed Coupon usage Validate order amount against coupon\u0026rsquo;s full_amount during checkout Mark used_at timestamp and link coupon to order Order refund Process refund based on discounted amount Remove coupon-order association Reset used_at to null An interesting JD-style feature worth implementing is redemption codes.\nCreate additional table:\n# Redemption Code Table `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `template_id` int(10) COMMENT \u0026#39;Coupon template ID\u0026#39;, `code` varchar(191) COMMENT \u0026#39;Redemption code\u0026#39;, `user_id` int(10) NULL COMMENT \u0026#39;Redeemer ID\u0026#39;, `used_at` timestamp NULL DEFAULT NULL COMMENT \u0026#39;Redemption time\u0026#39;, `created_at` timestamp NULL DEFAULT NULL COMMENT \u0026#39;Creation time\u0026#39;, `updated_at` timestamp NULL DEFAULT NULL COMMENT \u0026#39;Update time\u0026#39;, Workflow:\nOperations pre-generates codes Generate unique codes linked to templates Optionally bind to specific users User redemption process Input code in redemption zone Validate code usage status and user binding Generate user coupon from template Mark code as used ","date":"2019-09-04T23:06:17+08:00","image":"https://sethix.com/posts/2019090423/cover_hud4069996e191b85ffcb6b306fdfa5035_101580_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2019090423/","title":"Implementation of Coupon Functionality"},{"content":" This weekend, I updated the monday-shop system.\nThe most significant challenges came from upgrading laravel-admin to the latest version. This backend framework is particularly valuable as it allows developers to focus on core backend logic. First Issue: Composer Dependency Errors\nInitial composer install failed due to locked mirror sources. Solved by switching to Alibaba Cloud Composer Mirror.\nLaravel-admin Upgrade Challenges\nmonday-shop Key functionality affected:\nSoft Delete (下架) Restore (上架) Version-Specific Problems:\nSoft-deleted items couldn\u0026rsquo;t be processed by actions (throwing \u0026ldquo;model not found\u0026rdquo; errors)\nmonday-shop Force delete functionality failed (delete action only performed soft delete) Problem Solving Process Controller Analysis\nThe controller\u0026rsquo;s destroy method contained force delete logic, but requests weren\u0026rsquo;t reaching it:\nmonday-shop Routing Investigation\nAll actions routed through HandleController::handleAction:\nmonday-shop Model Retrieval Issue\nThe critical line: $model = $action-\u0026gt;retrieveModel($request);\nDefault implementation used Model::findOrFail(), incompatible with soft-deleted items:\nmonday-shop Solution: Override retrieveModel in custom Action class to include soft-deleted records:\nmonday-shop Force Delete Implementation Default Action Analysis\nDropdownActions contained basic delete action:\nmonday-shop Custom Force Delete Action\nRemoved default delete, added force delete implementation:\nmonday-shop Core logic using Laravel\u0026rsquo;s force delete:\nmonday-shop Final Outcome: Both soft delete management and force delete functionality now work as intended.\n","date":"2019-08-24T11:17:03+08:00","image":"https://sethix.com/posts/2019082411/cover_hu93efcade64f741b5bbbfb4d3d94a13c1_3355_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2019082411/","title":"[monday-shop] Issues and Solutions Encountered During Dependency Updates"},{"content":"Laravel has a powerful feature called service providers that makes it easy to access various services. However, this convenience comes at the cost of framework bloat. Here\u0026rsquo;s how to optimize unnecessary service providers.\nStep 1: Identify Unnecessary Service Providers Run php artisan package:discover or composer dump-auto to see all auto-loaded service providers:\nService Providers Step 2: Conditionally Load Providers Example 1: Admin Panel Optimization The encore/laravel-admin package (a backend panel) boots on every request. Instead, load it only when the URL contains admin:\nAdd it to extra.laravel.dont-discover in composer.json:\ncomposer.json Configuration Manually register it conditionally in AppServiceProvider: if (str_contains(request()-\u0026gt;getRequestUri(), \u0026#39;admin\u0026#39;)) { $this-\u0026gt;app-\u0026gt;register(\\Encore\\Admin\\AdminServiceProvider::class); } Example 2: Image Processing Optimization For intervention/image (used for image manipulation), defer loading until needed:\nAdd to dont-discover as above. Create a dedicated service class: class ImageService { public function __construct() { $this-\u0026gt;app-\u0026gt;register(\\Intervention\\Image\\ImageServiceProvider::class); } } Key Implementation Notes Dependency Handling: If a provider has dependencies: Register dependencies in AppServiceProvider::register() Boot in AppServiceProvider::boot() Use Laravel\u0026rsquo;s built-in Application::register() method to handle registration and booting automatically. Final Code Implementation Manual Registration Code Conditional Loading Implementation With these optimizations, you gain fine-grained control over external service providers while maintaining framework performance.\n","date":"2019-03-22T19:32:57+08:00","image":"https://sethix.com/posts/2019032219/cover_huc8ab171a934f0de687c88b465bd668e3_34365_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2019032219/","title":"Speed Up Your Framework: How to Reduce Service Provider Boot Time"},{"content":"Suppose we have the following graph:\n// 3 // e+-----------------+ // ^ | // 2| | // | | // 1 + 1 3 | // a +------\u0026gt; b +---\u0026gt; d +---+ | // + + | | // | | v | // 2 | |4 g \u0026lt;--+ // | | ^ // v v 1 | // c f +---+ // + ^ // | | // | 2 | // +------------------+ To find the shortest path from node a to node g, we can use the Dijkstra algorithm. Here\u0026rsquo;s how it works:\nConvert the graph to an adjacency matrix: array( \u0026#39;a\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; 1, \u0026#39;c\u0026#39; =\u0026gt; 2, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; INF, \u0026#39;g\u0026#39; =\u0026gt; INF), \u0026#39;b\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; 1, \u0026#39;e\u0026#39; =\u0026gt; 2, \u0026#39;f\u0026#39; =\u0026gt; INF, \u0026#39;g\u0026#39; =\u0026gt; INF), \u0026#39;c\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; 2, \u0026#39;g\u0026#39; =\u0026gt; INF), \u0026#39;d\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; 4, \u0026#39;g\u0026#39; =\u0026gt; 3), \u0026#39;e\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; INF, \u0026#39;g\u0026#39; =\u0026gt; 3), \u0026#39;f\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; INF, \u0026#39;g\u0026#39; =\u0026gt; 1), \u0026#39;g\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; INF, \u0026#39;g\u0026#39; =\u0026gt; INF), ); Initialize data structures: closedList: Tracks visited nodes (start with a) openList: Stores minimum distances from start node closedList(1) { a =\u0026gt; true } openList(7) { a =\u0026gt; INF b =\u0026gt; 1 c =\u0026gt; 2 d =\u0026gt; INF e =\u0026gt; INF f =\u0026gt; INF g =\u0026gt; INF } Iteration process: Find node with minimum distance in openList that\u0026rsquo;s not in closedList Update distances for adjacent nodes Mark node as visited in closedList First iteration:\nclosedList(2) { a =\u0026gt; true, b =\u0026gt; true } openList(7) { d =\u0026gt; 2 // b-\u0026gt;d (1+1) e =\u0026gt; 3 // b-\u0026gt;e (1+2) ...other values remain... } Final result:\nopenList(7) { a =\u0026gt; INF b =\u0026gt; 1 c =\u0026gt; 2 d =\u0026gt; 2 e =\u0026gt; 3 f =\u0026gt; 4 // c-\u0026gt;f (2+2) g =\u0026gt; 5 // d-\u0026gt;g (2+3) } The shortest path from a to g is 5 through path a-\u0026gt;b-\u0026gt;d-\u0026gt;g.\nImplementation code:\n\u0026lt;?php class Dijkstra { protected $matrix; public function __construct() { // Directed graph representation $this-\u0026gt;matrix = array( \u0026#39;a\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; 1, \u0026#39;c\u0026#39; =\u0026gt; 2, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; INF, \u0026#39;g\u0026#39; =\u0026gt; INF), \u0026#39;b\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; 1, \u0026#39;e\u0026#39; =\u0026gt; 2, \u0026#39;f\u0026#39; =\u0026gt; INF, \u0026#39;g\u0026#39; =\u0026gt; INF), \u0026#39;c\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; 2, \u0026#39;g\u0026#39; =\u0026gt; INF), \u0026#39;d\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; 4, \u0026#39;g\u0026#39; =\u0026gt; 3), \u0026#39;e\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; INF, \u0026#39;g\u0026#39; =\u0026gt; 3), \u0026#39;f\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; INF, \u0026#39;g\u0026#39; =\u0026gt; 1), \u0026#39;g\u0026#39; =\u0026gt; array(\u0026#39;a\u0026#39; =\u0026gt; INF, \u0026#39;b\u0026#39; =\u0026gt; INF, \u0026#39;c\u0026#39; =\u0026gt; INF, \u0026#39;d\u0026#39; =\u0026gt; INF, \u0026#39;e\u0026#39; =\u0026gt; INF, \u0026#39;f\u0026#39; =\u0026gt; INF, \u0026#39;g\u0026#39; =\u0026gt; INF), ); } public function search() { $start = \u0026#39;a\u0026#39;; $end = \u0026#39;g\u0026#39;; // Track visited nodes $closeList = [$start =\u0026gt; true]; // Store minimum distances $openList = $this-\u0026gt;matrix[$start]; foreach ($this-\u0026gt;matrix as $y =\u0026gt; $item) { $minIndex = $start; $minVal = INF; // Find minimum unvisited node foreach ($item as $x =\u0026gt; $val) { if (!isset($closeList[$x]) \u0026amp;\u0026amp; $openList[$x] \u0026lt; $minVal) { $minVal = $openList[$x]; $minIndex = $x; } } $closeList[$minIndex] = true; // Update distances foreach ($this-\u0026gt;matrix[$minIndex] as $k =\u0026gt; $v) { if (!isset($closeList[$k]) \u0026amp;\u0026amp; ($minVal + $v \u0026lt; $openList[$k])) { $openList[$k] = $minVal + $v; } } } echo \u0026#34;Shortest distance: \u0026#34; . $openList[$end]; } } ","date":"2019-03-13T12:52:43+08:00","image":"https://sethix.com/posts/2019031312/cover_hu687d2ce6bce4090c22aaaa70bc0208ed_4960_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2019031312/","title":"Dijkstra Algorithm"},{"content":"BFS stands for Breadth-First-Search\nDFS stands for Depth-first search\nA classic LeetCode problem \u0026ldquo;Number of Islands\u0026rdquo;:\nGiven a 2D grid map of 1s (land) and 0s (water), count the number of islands. An island is surrounded by water and formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are surrounded by water.\nInput:\n11000\n11000\n00100\n00011\nOutput: 3\nAlthough this problem is categorized under BFS, implementing it with DFS may be more intuitive.\nKey differences between the two search algorithms Assume we have an input grid:\n1 1 0 0 0 1 1 1 1 0 1 0 1 0 0 1 0 0 0 0 Both algorithms will return 1 as the answer DFS Characteristics DFS always prioritizes searching in one direction until reaching a dead end Then explores other directions from the end node Backtracks to previous nodes with unexplored paths Operates like a stack (Last-In-First-Out) Search order assumption: ↑↓←→ (up, down, left, right) Traversal sequence: 1 6 0 0 0 2 5 7 9 0 3 0 8 0 0 4 0 0 0 0 Starts at 1, reaches 4 via downward search. After backtracking, explores rightward to 5, then upward to 6. Continues to 7, 8, and finally 9. BFS Characteristics BFS explores all neighboring nodes first Expands search layer by layer Operates like a queue (First-In-First-Out) Search order assumption: ↑↓←→ (up, down, left, right) Traversal sequence: 1 3 0 0 0 2 5 7 9 0 4 0 8 0 0 6 0 0 0 0 Starts with 1 in the queue [1]. Processes neighbors to get [2,3], then expands to [4,5], [6,7], and finally [8,9]. View source code on GitHub\n","date":"2019-03-06T17:05:49+08:00","image":"https://sethix.com/posts/2019030617/cover_hu2bf19c8c4a79e9633c08162224932ef9_18518_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2019030617/","title":"DFS (Depth-First Search) and BFS (Breadth-First Search)"},{"content":"Recently encountered a linked list reversal problem on LeetCode:\nReverse a singly linked list. Example: Input: 1-\u0026gt;2-\u0026gt;3-\u0026gt;4-\u0026gt;5-\u0026gt;NULL Output: 5-\u0026gt;4-\u0026gt;3-\u0026gt;2-\u0026gt;1-\u0026gt;NULL Iterative Solution /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head) { struct ListNode *tmpHead = head, *nextNode; if (NULL == head) { return head; } while (NULL != head-\u0026gt;next) { // Move the next node of current \u0026#39;head\u0026#39; to real head position nextNode = head-\u0026gt;next; head-\u0026gt;next = head-\u0026gt;next-\u0026gt;next; nextNode-\u0026gt;next = tmpHead; tmpHead = nextNode; } return tmpHead; } Recursive Solution /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head) { if (NULL == head) { return NULL; } else if (NULL == head-\u0026gt;next) { return head; } struct ListNode *currNode = reverseList(head-\u0026gt;next); head-\u0026gt;next-\u0026gt;next = head; head-\u0026gt;next = NULL; return currNode; } /* Execution process: reverseList([1, 2, 3, 4, 5]) { reverseList([2, 3, 4, 5]) { reverseList([3, 4, 5]) { reverseList([4, 5]) { reverseList([5]) { // 1. Here next is NULL, return current node return 5; } // 2. Make 5 point to 4, set 4\u0026#39;s next to NULL [4, 5]-\u0026gt;next-\u0026gt;next = [4, 5]; [4, 5]-\u0026gt;next = NULL; return [5, 4]; } // 3. Make 4 point to 3, set 3\u0026#39;s next to NULL [3, 4]-\u0026gt;next-\u0026gt;next = [3, 4]; [3, 4]-\u0026gt;next = NULL; return [5, 4, 3]; } // 4. Make 3 point to 2, set 2\u0026#39;s next to NULL [2, 3]-\u0026gt;next-\u0026gt;next = [2, 3]; [2, 3]-\u0026gt;next = NULL; return [5, 4, 3, 2]; } // 5. Make 2 point to 1, set 1\u0026#39;s next to NULL [1, 2]-\u0026gt;next-\u0026gt;next = [1, 2]; [1, 2]-\u0026gt;next = NULL; return [5, 4, 3, 2, 1]; } */ Key points:\nRecursive approach uses the call stack to process nodes from end to start Each recursion level handles the pointer redirection: head-\u0026gt;next-\u0026gt;next = head makes next node point to current node head-\u0026gt;next = NULL breaks the original link The deepest recursion returns the new head (original tail node) which propagates back through all recursion levels ","date":"2019-02-18T15:43:12+08:00","image":"https://sethix.com/posts/2019021815/cover_huf9931d5d1b9b1bd42af81d6401bba187_19714_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2019021815/","title":"Reverse Linked List - Recursive Approach"},{"content":"I previously used ab (ApacheBench), the built-in stress testing tool from Apache, but found it less convenient. After some research, I discovered a tool called JMeter.\nInstalling JDK Since JMeter is developed in Java, we need a Java Runtime Environment (JRE). For simplicity, we\u0026rsquo;ll install the full JDK (Java Development Kit):\nVisit the official Oracle download page:\nhttps://www.oracle.com/technetwork/java/javase/downloads/index.html Select JDK download:\nJDK Download Accept the license agreement and download the appropriate version for your OS (Windows in this case):\nJDK Version Run the installer with default settings (note the installation directory):\nJDK Installation Configuring Environment Variables Locate the JDK\u0026rsquo;s bin directory (e.g., C:\\Program Files\\Java\\jdk-11.0.1\\bin) and copy the path.\nJDK Bin Path Add to System Path: Right-click Computer → Properties → Advanced system settings Environment Variables → Select Path → Edit\nEnvironment Variables Paste the JDK bin path into the Path variable:\nPath Configuration Verify by running java --version in Command Prompt:\nJava Version Check Installing JMeter Download JMeter from the official site:\nhttp://jmeter.apache.org/download_jmeter.cgi\nJMeter Download Extract the ZIP file to your preferred directory (JMeter is portable). Launch JMeter by running bin/jmeter.bat:\nJMeter Launch Set Chinese localization (optional) by editing jmeter.properties: language=zh_CN Localization Setting Usage Guide Create a new test plan: File → New\nNew Test Plan Add a Thread Group: Right-click Test Plan → Add → Threads (Users) → Thread Group\nAdd Thread Group Configure Thread Group: Number of Threads (users): 200 (concurrent users) Ramp-Up Period: 2 seconds (100 users per second) Loop Count: 5 (total requests = 200 × 5 = 1000)\nThread Group Settings Add an HTTP Request: Right-click Thread Group → Add → Sampler → HTTP Request\nAdd HTTP Request Configure HTTP Request: Server Name/IP: example.com Path: /api/test\nHTTP Request Settings Add listeners for results: View Results Tree Summary Report\nAdd Listeners Run the test (Run → Start) and save the test plan when prompted:\nRun Test View results in listeners:\nTest Results Aggregate Report Aggregate Report Metrics Explained Metric Description Label Name of the request (e.g., HTTP Request) # Samples Total requests sent to the server Average Average response time per request Median 50th percentile response time 90% Line 90th percentile response time 95% Line 95th percentile response time 99% Line 99th percentile response time Min Minimum response time Max Maximum response time Error % Error rate = (Failed requests / Total requests) × 100 Throughput Requests per second (RPS) Received KB/sec Data received per second from the server Sent KB/sec Data sent per second from the client ","date":"2018-12-04T11:56:11+08:00","image":"https://sethix.com/posts/2018120411/cover_hud0f934640b295715eebf91c38070e4af_90426_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018120411/","title":"Stress Testing with JMeter"},{"content":"When working with UTC time formats that need conversion to local time (e.g., UTC+8), here\u0026rsquo;s a breakdown of the process for the input format yyyy-MM-ddTHH:mm:ss.SSSZ:\nyyyy: 4-digit year MM: 2-digit month (01-12) dd: 2-digit day (01-31) T: Date/time separator HH: 24-hour format hour (00-23) mm: Minutes (00-59) ss: Seconds (00-59) SSS: Milliseconds (3 digits) Z: Timezone offset (e.g., +0100 for UTC+1) Example Conversion:\nInput: 2018-01-01T12:00:00.000+0100 (UTC+1)\nLocal Output (UTC+8): 2018-01-01 19:00:00.000 (+7 hours)\nImplementation using Carbon:\n\u0026lt;?php use Carbon\\Carbon; // Input time with timezone offset $input = \u0026#39;2018-01-01T12:00:00.000+0100\u0026#39;; // Parse UTC time with offset $carbon = Carbon::parse($input); // Convert to China Standard Time (UTC+8) $carbon-\u0026gt;setTimezone(\u0026#39;Asia/Shanghai\u0026#39;); // or \u0026#39;PRC\u0026#39; // Output with milliseconds (Y-m-d H:i:s.u) echo $carbon-\u0026gt;format(\u0026#39;Y-m-d H:i:s.u\u0026#39;); // 2018-01-01 19:00:00.000 Key Notes:\nUse Carbon::parse() for ISO 8601 formatted strings Prefer Asia/Shanghai over PRC for clearer timezone identification Include .u in format for milliseconds display Works for any timezone offset in the input (e.g., +0530, -0500) For non-PHP implementations, similar logic applies using native datetime libraries with timezone support.\n","date":"2018-11-15T17:15:54+08:00","image":"https://sethix.com/posts/2018111517/cover_hu25430e192e92736ffcee4a5b4157edd3_26096_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018111517/","title":"Converting UTC Time to Local Time"},{"content":"Recently encountered an issue while implementing permission control for API endpoints.\nThis builds upon our previous permission control method: Using Route-Based Permission Control in Laravel (Applicable Beyond Laravel, as a Conceptual Approach)\nWe have two route aliases:\nPaginated city list: cities.index\nComplete city list: cities.index.all\nThese represent two separate permissions. To ensure users with only the cities.index permission can also access cities.index.all (since both belong to list operations under normal logic), we need to make minor adjustments to our validation logic.\n\u0026lt;?php namespace App\\Http\\Middleware; use App\\Models\\Permission; use App\\Models\\User; use Closure; use Illuminate\\Http\\Request; use Illuminate\\Support\\Facades\\Route; use Symfony\\Component\\HttpFoundation\\Response; use Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException; class AdminPermission { /** * Process: * 1. Get current route name * 2. Check if route requires permission * 3. Grant access or throw permission exception * * @param Request $request * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { $route = Route::currentRouteName(); // This route has no name if (is_null($route)) { return $next($request); } // Handle routes ending with .all if (ends_with($route, \u0026#39;.all\u0026#39;)) { $route = substr($route, 0, -4); } // Check if route requires permission // Consider using cache for performance optimization if ($permission = Permission::query()-\u0026gt;where(\u0026#39;route\u0026#39;, $route)-\u0026gt;first()) { /** * @var $user User */ $user = $request-\u0026gt;user(); // Verify user permission if (! $user-\u0026gt;hasPermissionTo($permission)) { throw new UnauthorizedHttpException(\u0026#39;permission\u0026#39;, trans(\u0026#39;error_permission.denied\u0026#39;), null, Response::HTTP_FORBIDDEN); } } return $next($request); } } Key implementation details:\nNormalizes route names ending with .all by removing the suffix Maintains existing permission verification logic Allows inherited permissions between paginated and complete list views This approach ensures users with list permissions automatically get access to both paginated and complete list variations without duplicate permission assignments.\n","date":"2018-10-17T16:12:05+08:00","image":"https://sethix.com/posts/2018101716/cover_hu4269ff0cf5970e5c6a6e13cff52a0cbd_26850_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018101716/","title":"In Route Permission Control, a Paginated List Permission Can Simultaneously Control All List Permissions"},{"content":" We often encounter scenarios like ticket purchasing queries that require date range validation: the start date must be greater than or equal to today, and the end date must be greater than or equal to the start date. Version Laravel 5.5.40 PHP 7.1 Implementation Steps Create a Form Request:\nLaravel Note: Remember to return true in the authorize() method since we\u0026rsquo;re handling authentication elsewhere\nBasic validation rules:\nLaravel Special validation challenge:\nInitial attempt to validate start_date using an extra field:\nLaravel Testing shows this approach doesn\u0026rsquo;t work as expected\nDebugging reveals the validation data is captured before custom rules:\nLaravel Laravel Solution: Override prepareForValidation()\nLaravel This ensures curr_date is available during validation\nFinal working validation:\nLaravel Technical Analysis IoC Container handles dependency injection for form requests Validation Workflow: prepareForValidation() (custom preparation) Create validator instance with current request data Execute validation rules Key implementation detail: protected function prepareForValidation() { $this-\u0026gt;merge([\u0026#39;curr_date\u0026#39; =\u0026gt; date(\u0026#39;Y-m-d\u0026#39;)]); } Alternative approach using built-in today keyword: \u0026#39;start_date\u0026#39; =\u0026gt; \u0026#39;required|date|after_or_equal:today\u0026#39;, Leverages PHP\u0026rsquo;s strtotime() recognition of \u0026ldquo;today\u0026rdquo; Validation Flowchart graph TD A[Request Initiated] --\u0026gt; B[Resolve FormRequest] B --\u0026gt; C[Prepare Validation Data] C --\u0026gt; D[Execute Validation Rules] D --\u0026gt; E{Validation Pass?} E --\u0026gt;|Yes| F[Process Request] E --\u0026gt;|No| G[Return Validation Errors] This approach ensures robust date validation while maintaining Laravel\u0026rsquo;s elegant syntax and validation capabilities.\n","date":"2018-09-19T11:51:03+08:00","image":"https://sethix.com/posts/2018091911/cover_hua8cf64c1f09f0589a3198cdb8597ef74_3712_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018091911/","title":"Elegantly Validate Date Must Be Greater Than Today in Laravel"},{"content":" From Baidu Encyclopedia:\nA macro in computer science refers to batch processing rules. Generally, it\u0026rsquo;s a pattern or syntactic substitution that defines how specific inputs (usually strings) are transformed into corresponding outputs (also strings) according to predefined rules. This substitution occurs during preprocessing, called macro expansion.\nMy first encounter with macros was during a university computer basics course when the professor demonstrated Office macros. Though I didn\u0026rsquo;t fully grasp it then, I remembered macros as powerful tools that could simplify repetitive tasks. Today we\u0026rsquo;ll explore macro operations in Laravel Complete Source Code First \u0026lt;?php namespace Illuminate\\Support\\Traits; use Closure; use ReflectionClass; use ReflectionMethod; use BadMethodCallException; trait Macroable { /** * The registered string macros. * * @var array */ protected static $macros = []; /** * Register a custom macro. * * @param string $name * @param object|callable $macro * * @return void */ public static function macro($name, $macro) { static::$macros[$name] = $macro; } /** * Mix another object into the class. * * @param object $mixin * @return void */ public static function mixin($mixin) { $methods = (new ReflectionClass($mixin))-\u0026gt;getMethods( ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED ); foreach ($methods as $method) { $method-\u0026gt;setAccessible(true); static::macro($method-\u0026gt;name, $method-\u0026gt;invoke($mixin)); } } /** * Checks if macro is registered. * * @param string $name * @return bool */ public static function hasMacro($name) { return isset(static::$macros[$name]); } /** * Dynamically handle calls to the class. * * @param string $method * @param array $parameters * @return mixed * * @throws \\BadMethodCallException */ public static function __callStatic($method, $parameters) { if (! static::hasMacro($method)) { throw new BadMethodCallException(\u0026#34;Method {$method} does not exist.\u0026#34;); } if (static::$macros[$method] instanceof Closure) { return call_user_func_array(Closure::bind(static::$macros[$method], null, static::class), $parameters); } return call_user_func_array(static::$macros[$method], $parameters); } /** * Dynamically handle calls to the class. * * @param string $method * @param array $parameters * @return mixed * * @throws \\BadMethodCallException */ public function __call($method, $parameters) { if (! static::hasMacro($method)) { throw new BadMethodCallException(\u0026#34;Method {$method} does not exist.\u0026#34;); } $macro = static::$macros[$method]; if ($macro instanceof Closure) { return call_user_func_array($macro-\u0026gt;bindTo($this, static::class), $parameters); } return call_user_func_array($macro, $parameters); } } Key Components Explained Macroable::macro Method public static function macro($name, $macro) { static::$macros[$name] = $macro; } This simple method stores macros in a static array. The $macro parameter can accept either a closure or an object (thanks to PHP\u0026rsquo;s magic methods):\nclass Father { public function __invoke() { echo __CLASS__; } } class Child { use \\Illuminate\\Support\\Traits\\Macroable; } // Register macro Child::macro(\u0026#39;show\u0026#39;, new Father); // Output: Father (new Child)-\u0026gt;show(); Macroable::mixin Method\nInjects methods from another object: public static function mixin($mixin) { $methods = (new ReflectionClass($mixin))-\u0026gt;getMethods( ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED ); foreach ($methods as $method) { $method-\u0026gt;setAccessible(true); static::macro($method-\u0026gt;name, $method-\u0026gt;invoke($mixin)); } } // Usage example class Father { public function say() { return fn() =\u0026gt; echo \u0026#39;say\u0026#39;; } protected function eat() { return fn() =\u0026gt; echo \u0026#39;eat\u0026#39;; } } Child::mixin(new Father); // All methods become available (new Child)-\u0026gt;say(); // Output: say (new Child)-\u0026gt;eat(); // Output: eat Macroable::hasMacro Method\nSimple existence check: public static function hasMacro($name) { return isset(static::$macros[$name]); } Magic Methods __call \u0026amp; __callStatic\nEnable dynamic method handling: public function __call($method, $parameters) { if (!static::hasMacro($method)) { throw new BadMethodCallException(\u0026#34;Method {$method} does not exist.\u0026#34;); } $macro = static::$macros[$method]; if ($macro instanceof Closure) { return call_user_func_array($macro-\u0026gt;bindTo($this, static::class), $parameters); } return call_user_func_array($macro, $parameters); } // Example with context binding Child::macro(\u0026#39;show\u0026#39;, function() { echo $this-\u0026gt;name; // Accesses Child\u0026#39;s property }); (new Child)-\u0026gt;show(); // Output: father Implementing Macros in Laravel Classes Many Laravel classes use the Macroable trait (e.g., Illuminate\\Filesystem\\Filesystem). To add custom methods:\nRegister macros in App\\Providers\\AppServiceProvider: // app/Providers/AppServiceProvider.php public function register() { Filesystem::macro(\u0026#39;customMethod\u0026#39;, function($param) { return \u0026#34;Working with: $param\u0026#34;; }); } Create test route: // routes/web.php Route::get(\u0026#39;/test-macro\u0026#39;, function() { return Storage::customMethod(\u0026#39;demo\u0026#39;); }); Visit /test-macro to see \u0026ldquo;Working with: demo\u0026rdquo; output. This approach extends functionality without modifying core classes, demonstrating Laravel\u0026rsquo;s elegant extensibility through macros.\n","date":"2018-07-10T12:46:43+08:00","image":"https://sethix.com/posts/2018071012/cover_hube5dc19039ec03a3745c0b835d43db81_17104_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018071012/","title":"The Concise Yet Powerful Macroable Macros in Laravel"},{"content":" When developing APIs, authentication is inevitable. I use jwt-auth for this purpose. A common issue in authentication is token expiration. In the default settings of config/jwt.php, the expiration time is one hour. For better security, I\u0026rsquo;ve set it to 5 minutes. Forcing users to re-login every 5 minutes would lead to terrible user experience. This is where token refresh functionality becomes essential. Normally, we create a dedicated token refresh endpoint. When expired, frontend sends the old token to this endpoint to get a new one. For frontend convenience, I implemented backend auto-refresh until final expiration using this approach: Implementing API User Authentication and Painless Token Refresh with Jwt-Auth Here\u0026rsquo;s where the pitfall emerged: Authentication-required endpoints with token refresh middleware: \u0026lt;?php namespace App\\Http\\Middleware; use App\\Services\\StatusServe; use Closure; use Symfony\\Component\\HttpKernel\\Exception\\UnauthorizedHttpException; use Tymon\\JWTAuth\\Exceptions\\JWTException; use Tymon\\JWTAuth\\Exceptions\\TokenExpiredException; use Tymon\\JWTAuth\\Http\\Middleware\\BaseMiddleware; class CheckUserLoginAndRefreshToken extends BaseMiddleware { /** * Check user authentication. If token expires, * refresh token and return in response headers */ public function handle($request, Closure $next) { $this-\u0026gt;checkForToken($request); try { if ($this-\u0026gt;auth-\u0026gt;parseToken()-\u0026gt;authenticate()) { return $next($request); } throw new UnauthorizedHttpException(\u0026#39;jwt-auth\u0026#39;, \u0026#39;User not found\u0026#39;); } catch (TokenExpiredException $e) { try { $token = $this-\u0026gt;auth-\u0026gt;refresh(); $id = $this-\u0026gt;auth -\u0026gt;manager() -\u0026gt;getPayloadFactory() -\u0026gt;buildClaimsCollection() -\u0026gt;toPlainArray()[\u0026#39;sub\u0026#39;]; auth()-\u0026gt;onceUsingId($id); } catch (JWTException $e) { throw new UnauthorizedHttpException(\u0026#39;jwt-auth\u0026#39;, $e-\u0026gt;getMessage(), null, StatusServe::HTTP_PAYMENT_REQUIRED); } } return $this-\u0026gt;setAuthenticationHeader($next($request), $token); } } Optional authentication endpoints using default jwt-auth middleware: \u0026lt;?php namespace Tymon\\JWTAuth\\Http\\Middleware; use Closure; use Exception; class Check extends BaseMiddleware { /** * Handle optional authentication */ public function handle($request, Closure $next) { if ($this-\u0026gt;auth-\u0026gt;parser()-\u0026gt;setRequest($request)-\u0026gt;hasToken()) { try { $this-\u0026gt;auth-\u0026gt;parseToken()-\u0026gt;authenticate(); } catch (Exception $e) { // Silent failure for optional auth } } return $next($request); } } Initially, everything seemed fine until we noticed inconsistent like status display on article lists for logged-in users. Debugging revealed that optional endpoints failed to refresh tokens. Users would see correct like status after visiting authenticated pages (which refreshed tokens), but lose it after token expiration. The root cause: optional endpoints didn\u0026rsquo;t handle token refresh. When token expired: Article list endpoint (optional auth) → No user data Profile page (required auth) → Token refreshed → Article list works again Solution: Create custom optional auth middleware with refresh handling: \u0026lt;?php namespace App\\Http\\Middleware; use Closure; use Exception; use Tymon\\JWTAuth\\Exceptions\\TokenExpiredException; class OptionalCheck extends BaseMiddleware { public function handle($request, Closure $next) { if ($this-\u0026gt;auth-\u0026gt;parser()-\u0026gt;setRequest($request)-\u0026gt;hasToken()) { try { $this-\u0026gt;auth-\u0026gt;parseToken()-\u0026gt;authenticate(); } catch (TokenExpiredException $e) { // Add token refresh logic here // Similar to required auth middleware return $this-\u0026gt;setAuthenticationHeader($next($request), $token); } catch (Exception $e) { // Handle other exceptions } } return $next($request); } } Concurrency Consideration Token refresh race condition scenario:\n# Token_1 expires # Request A comes first, gets new Token_2 # Request B (using Token_1) comes slightly later # Server blacklists Token_1 after refresh token_1 returns token_2 A: ------------\u0026gt; server ------------\u0026gt; success token_1 (now blacklisted) B: ------------\u0026gt; server ------------\u0026gt; failure Solution: Set blacklist grace period in jwt.php:\n\u0026#39;blacklist_grace_period\u0026#39; =\u0026gt; 5 // 5-second buffer This allows a short window where expired tokens remain valid after refresh.\n","date":"2018-06-24T12:04:42+08:00","image":"https://sethix.com/posts/2018062412/cover_hu6331f63620e925a109165fba5c4ee2ac_63195_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018062412/","title":"A Pitfall When Developing Optional Token-Passing API Interfaces"},{"content":"To validate a numeric exact value, I referred to the form validation documentation:\nsize:value\nThe field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to the integer value. For arrays, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.\nOriginal validation rule:\n$data = [\u0026#39;age\u0026#39; =\u0026gt; 9]; $validator = \\Illuminate\\Support\\Facades\\Validator::make($data, [\u0026#39;age\u0026#39; =\u0026gt; \u0026#39;required|size:9\u0026#39;]); if ($validator-\u0026gt;fails()) { dd($validator-\u0026gt;errors()-\u0026gt;first()); } dd(\u0026#39;pass\u0026#39;); I expected it to validate numbers directly when the input 9 is an integer. However, it returned an error message:\nThe age must be 9 characters.\nThis message clearly indicates string length validation. Upon further investigation, I realized we need to add the numeric or integer rule.\nCode analysis:\nTrace validation logic in \\Illuminate\\Validation\\Validator::fails()\nLaravel Core validation method: $this-\u0026gt;validateAttribute($attribute, $rule);\nPre-validation filtering for file uploads\nLaravel Dynamic method generation for validation rules\nLaravel (The resolved method here is validateSize)\nLocate the method in ValidatesAttributes::validateSize\nLaravel Key logic checks $hasNumeric condition\nLaravel $hasNumeric is determined by:\nLaravel Validation flow without numeric/integer rules\nLaravel Laravel Missing numeric check returns null, making $hasNumeric false:\nLaravel Conclusion: Always combine size with numeric or integer when validating numbers:\n\u0026#39;age\u0026#39; =\u0026gt; \u0026#39;required|integer|size:9\u0026#39; // or \u0026#39;age\u0026#39; =\u0026gt; \u0026#39;required|numeric|size:9\u0026#39; ","date":"2018-06-01T10:15:17+08:00","image":"https://sethix.com/posts/2018060110/cover_hua8cf64c1f09f0589a3198cdb8597ef74_3712_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018060110/","title":"Laravel Form size Validation for Numbers"},{"content":"Origin Solutions always outnumber problems, making problem discovery more valuable than problem-solving itself. The story began when debugging model events - I randomly inserted a string ID (non-standard UUID) into the database and found the model couldn\u0026rsquo;t be retrieved by this ID in my model events. When encountering issues, it\u0026rsquo;s worth checking Laravel\u0026rsquo;s issue tracker to find solvable problems. Progress After verifying my code wasn\u0026rsquo;t faulty through step-by-step debugging\nController Event Log Discovered the ID returned by belongsToMany::sync method was incorrect\nbelongsToMany Identified integer overflow in InteractsWithPivotTable::caseKey source code\nInteger overflow Confirmed the issue was numeric overflow from type casting. Even with primary key set as string in model, incorrect casting occurred\nOverflow Submitted an issue Laravel team member tillkruss suggested submitting a PR Fixed by checking primary key type before casting. Initial PR was rejected due to missing tests. Added database tests referencing existing test cases. Final merged PR: 5.7 Improve the return value of the caseKey method Conclusion First PR submission taught me the importance of rigor in large projects Always include clear code comments and comprehensive tests Detailed PR descriptions are crucial for maintainers The community offers great support for contributors Join Laravel learning group (QQ: 584453488) for more discussions Key takeaways: Preserve technical terms like uuid, belongsToMany::sync, and GitHub references. Maintain code snippets and links exactly as original.\n","date":"2018-05-14T16:17:35+08:00","image":"https://sethix.com/posts/2018051416/cover_hu1a4fadea656f0f127d990ebb8cbec99f_7987_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018051416/","title":"How I Contributed to Laravel's Source Code for the First Time"},{"content":"Starting to learn data structures\nToday I changed the code font I use. Previously I used console which looked good, but today I found a more preferable style Source Code Pro.\nHere are two screenshots - it\u0026rsquo;s quite pleasing!\nSource Code Pro Source Code Pro Now let\u0026rsquo;s get to the main topic: linked list operations\nNode Class First we need a Node class to store data \u0026lt;?php namespace LinkedList; class Node { /** * @var $data integer */ public $data; /** * Pointer to next node * * @var $next Node */ public $next; public function __construct(int $data = null) { // Initialize data assignment, can also be assigned via $node-\u0026gt;data = X; $this-\u0026gt;data = $data; } } Linked List Manager Class (For node operations) We\u0026rsquo;ll break down the manager class code into sections due to its length Head Insertion As the name suggests, insert at the head If list is empty, initialize with current node If not empty, make new node the head public function insertHead(int $data) : bool { $newNode = new Node($data); $newNode-\u0026gt;next = $this-\u0026gt;head; $this-\u0026gt;head = $newNode; return true; } Insert at Position (index=0 is head, returns false for invalid positions) public function insert(int $index = 0, int $data) : bool { if (is_null($this-\u0026gt;head) || $index === 0) { return $this-\u0026gt;insertHead($data); } $currNode = $this-\u0026gt;head; $startIndex = 1; for ($currIndex = $startIndex; ! is_null($currNode); ++ $currIndex) { if ($currIndex === $index) { $newNode = new Node($data); $newNode-\u0026gt;next = $currNode-\u0026gt;next; $currNode-\u0026gt;next = $newNode; return true; } $currNode = $currNode-\u0026gt;next; } return false; } Usage example:\n\u0026lt;?php // Autoload code omitted, see github require __DIR__.\u0026#39;/../vendor/bootstrap.php\u0026#39;; // Instantiate a linked list manager $manager = new \\LinkedList\\Manager(); // 8 $manager-\u0026gt;insertHead(8); // 5 8 $manager-\u0026gt;insertHead(5); // 1 5 8 $manager-\u0026gt;insertHead(1); // 1 2 5 8 $manager-\u0026gt;insert(1, 2); // false (insufficient nodes for position 5) $manager-\u0026gt;insert(5, 4); // 1 2 5 8 9 $manager-\u0026gt;insertEnd(9); // Returns 3 $manager-\u0026gt;find(8); // Result: 1 2 8 9 $manager-\u0026gt;delete(2); Search Operation Simply traverse the list to find value public function find(int $data) : int { $currNode = $this-\u0026gt;head; for ($i = 0; ! is_null($currNode); ++ $i) { if ($currNode-\u0026gt;data === $data) { return $i; } $currNode = $currNode-\u0026gt;next; } return -1; } Delete Operation public function delete(int $index) : bool { if (is_null($this-\u0026gt;head)) { return false; } elseif ($index === 0) { $this-\u0026gt;head = $this-\u0026gt;head-\u0026gt;next; } $startIndex = 1; $currNode = $this-\u0026gt;head; for ($i = $startIndex; ! is_null($currNode-\u0026gt;next); ++ $i) { if ($index === $i) { $currNode-\u0026gt;next = $currNode-\u0026gt;next-\u0026gt;next; break; } $currNode = $currNode-\u0026gt;next; } return true; } End The code has been hosted on github Will continue learning data structures (doubly linked lists, trees, etc.) when time permits! ","date":"2018-04-24T10:08:57+08:00","image":"https://sethix.com/posts/2018042410/cover_hu5711d900eadf636f7f45569b8d37ebcc_17616_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018042410/","title":"Implementation of Linked List in PHP"},{"content":" A previous blog briefly introduced Using RESTful in Laravel This article explains various RESTful-style route writing conventions. While not necessarily authoritative, these patterns are semantically meaningful in practice. Base Routing Typically grouped with a common prefix: Always follows API + version format /api/v1 Basic Parameters Pagination parameters using QueryString: limit page Example: /url?limit=10\u0026amp;page=1 Multi-parameter sorting: Example: /url?desc=created_at,id\u0026amp;asc=grade,updated_at Fundamental Routes List categories: method: GET /categories Create category: method: POST /categories Delete category: method: DELETE /categories/{category} Get single category: method: GET /categories/{category} Update category: method: PUT /categories/{category} Intermediate Routes Get articles under category: method: GET /categories/{category}/articles Get articles with tag: method: GET /tags/{tag}/articles Batch delete articles (avoid when possible): method: DELETE /articles/batch?id=1,2,3 Authentication Routes Common implementations:\nLogin:\nmethod: POST /login Logout:\nmethod: POST /logout RESTful-compliant alternatives:\nCreate token (login):\nmethod: POST /tokens Delete token (logout):\nmethod: DELETE /tokens/{token} Multi-word Route Handling For SEO-friendly multi-word routes: Use hyphen-separated format Get articles by type: method: GET /article-types/{article_type}/articles ","date":"2018-04-05T21:11:41+08:00","image":"https://sethix.com/posts/2018040521/cover_hu6f9b4ab2376a566fc6ec539e419ced2a_24027_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018040521/","title":"RESTful Routing URL Naming Conventions"},{"content":"When developing a WeChat auto-reply demo, I encountered this scenario:\nReceive specific messages Reply with predefined content based on keywords stored in database Requires partial matching with fuzzy database queries For conventional fuzzy matching, everyone knows to use LIKE. Given this table structure:\nid keyword reply 1 David This is David 2 KingDavid This is David If the input keyword is \u0026ldquo;David\u0026rdquo;, we need to find all records containing David. The SQL would be:\nSELECT * FROM table_name WHERE keyword LIKE '%David%'\nNow consider a reverse scenario: We store only one record in the database that can match both \u0026ldquo;David\u0026rdquo; and \u0026ldquo;King David\u0026rdquo; with the same reply. This requires reverse fuzzy lookup. Table data:\nid keyword reply 1 %David% This is David The corresponding reverse lookup SQL would be:\nSELECT * FROM table_name WHERE 'David' LIKE keyword\nThis query pattern inverts the conventional fuzzy search logic - instead of matching database entries against user input, we match user input against predefined patterns in the database. The % wildcards in the database\u0026rsquo;s keyword field enable flexible partial matching from the user\u0026rsquo;s input perspective.\n","date":"2018-04-01T21:56:48+08:00","image":"https://sethix.com/posts/2018040121/cover_hu7c4584e122e33b56c749588831ebe075_19251_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018040121/","title":"MySQL Reverse Fuzzy Lookup"},{"content":"Environment Specifications Linux version: CentOS7 Nginx: Default version MySQL: MariaDB PHP: Version PHP71 Linux Open required ports after server setup: 80 for HTTP 443 for HTTPS (optional) 3306 for remote MySQL connections Nginx Install Nginx on CentOS: yum install nginx -y Start Nginx: nginx Enable auto-start: systemctl enable nginx Configuration: Default config file: /etc/nginx/nginx.conf Add include /etc/nginx/conf.d/*.conf; to load custom configurations Remove default server block and create new config: vi /etc/nginx/conf.d/blog.conf Sample configuration: server { listen 80; server_name localhost; root /var/www/blog; index index.php index.html index.htm; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \\.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } Reload Nginx: nginx -s reload MySQL Install MariaDB: yum -y install mariadb mariadb-server Start service: systemctl start mariadb Enable auto-start: systemctl enable mariadb Initialize configuration: mysql_secure_installation Create remote user: CREATE USER \u0026#39;username\u0026#39;@\u0026#39;localhost\u0026#39; IDENTIFIED BY \u0026#39;password\u0026#39;; GRANT ALL PRIVILEGES ON *.* TO \u0026#39;username\u0026#39;@\u0026#39;%\u0026#39; IDENTIFIED BY \u0026#39;password\u0026#39;; FLUSH PRIVILEGES; PHP Add repositories: rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm Install PHP71 and extensions: yum install php71w php71w-fpm php71w-mysqlnd Start PHP-FPM: systemctl start php-fpm Enable auto-start: systemctl enable php-fpm Web Test Create test file: mkdir -p /var/www/blog echo \u0026#34;\u0026lt;?php phpinfo();\u0026#34; \u0026gt; /var/www/blog/index.php Visit server IP to verify PHP configuration END ","date":"2018-03-31T11:55:27+08:00","image":"https://sethix.com/posts/2018033111/cover_hu5d392ecc80e187b8fb88d343464e2578_23207_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018033111/","title":"Quickly Set Up an LNMP Environment"},{"content":"Start Permission design is a crucial feature for backend management systems. PHP already has many mature packages for this purpose, so we don\u0026rsquo;t need to reinvent the wheel (though you certainly can if preferred).\nPS Here are two common historical approaches for permission verification:\nVerify required permissions individually on each page Centralized verification via middleware First, let\u0026rsquo;s examine a simplified database schema (retaining only critical fields) with its ER diagram: Database Model Diagram (Note: In this design, users don\u0026rsquo;t directly possess permissions but inherit them through roles. Many packages allow direct user permissions.)\nModels 1. User Model \u0026lt;?php namespace App\\Models; use Illuminate\\Notifications\\Notifiable; use Illuminate\\Foundation\\Auth\\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * Relationship with Role model */ public function roles() { return $this-\u0026gt;belongsToMany(Role::class); } /** * Check if user has a specific permission * 1. Get required permission name * 2. Iterate through user\u0026#39;s roles * 3. Check if any role has the permission */ public function hasPermission($permissionName) { foreach ($this-\u0026gt;roles as $role) { if ($role-\u0026gt;permissions()-\u0026gt;where(\u0026#39;name\u0026#39;, $permissionName)-\u0026gt;exists()) { return true; } } return false; } } 2. Role Model \u0026lt;?php namespace App\\Models; class Role extends Model { public function users() { return $this-\u0026gt;belongsToMany(User::class); } public function permissions() { return $this-\u0026gt;belongsToMany(Permission::class); } } 3. Permission Model \u0026lt;?php namespace App\\Models; class Permission extends Model { public function roles() { return $this-\u0026gt;belongsToMany(Role::class); } } Database Seeding Sample data:\n# Users +----+-------+----------+ | id | name | password | +----+-------+----------+ | 1 | gps | 123456 | | 2 | david | 123456 | # Roles +----+-------+ | id | name | +----+-------+ | 1 | admin | # Permissions +----+-----------------+ | id | name | +----+-----------------+ | 1 | create_product | | 2 | delete_product | # role_user (User gps has admin role) +---------+---------+ | role_id | user_id | +---------+---------+ | 1 | 1 | # permission_role (Admin role has product permissions) +---------+---------------+ | role_id | permission_id | +---------+---------------+ | 1 | 1 | | 1 | 2 | Approach 1: Page-Level Verification \u0026lt;?php namespace App\\Http\\Controllers; use App\\Models\\Product; class ProductsController extends Controller { public function store(Request $request) { if (!$request-\u0026gt;user()-\u0026gt;hasPermission(\u0026#39;create_product\u0026#39;)) { abort(403); } // Business logic return back()-\u0026gt;with(\u0026#39;status\u0026#39;, \u0026#39;Product created\u0026#39;); } public function destroy(Product $product) { if (!$request-\u0026gt;user()-\u0026gt;hasPermission(\u0026#39;delete_product\u0026#39;)) { abort(403); } // Business logic return back()-\u0026gt;with(\u0026#39;status\u0026#39;, \u0026#39;Product deleted\u0026#39;); } } Approach 2: Centralized Middleware Verification Enhance the permissions table with a route column:\n# permissions +----+-----------------+------------------+ | id | name | route | +----+-----------------+------------------+ | 1 | create_product | products.store | | 2 | delete_product | products.destroy | Create a middleware:\n\u0026lt;?php namespace App\\Http\\Middleware; use Closure; use Illuminate\\Support\\Facades\\Route; use App\\Models\\Permission; class PermissionAuth { public function handle($request, Closure $next) { $route = Route::currentRouteName(); if ($permission = Permission::where(\u0026#39;route\u0026#39;, $route)-\u0026gt;first()) { if (!auth()-\u0026gt;user()-\u0026gt;hasPermission($permission-\u0026gt;name)) { return response()-\u0026gt;view(\u0026#39;errors.403\u0026#39;, [ \u0026#39;status\u0026#39; =\u0026gt; \u0026#34;Insufficient permissions. Required: {$permission-\u0026gt;name}\u0026#34; ]); } } return $next($request); } } END For Laravel implementations, consider using the mature package:\nhttps://github.com/spatie/laravel-permission\n","date":"2018-03-27T12:53:51+08:00","image":"https://sethix.com/posts/2018032712/cover_hu4730eba3556cd067bf0c5e4805eba7d2_34359_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018032712/","title":"Permission Control via Routing in Laravel (Not Limited to Laravel, Just a Conceptual Approach)"},{"content":"When I first started learning, I used WordPress for blogging. Later I experimented with GitHub, tried the sophisticated GitHub Pages blog platform for quite some time, but found pure static blogs couldn\u0026rsquo;t fully meet my needs. Though various plugins could compensate, it remained a workaround.\nEventually I returned to WordPress.\nCreating a CODING Repository Visit the official website (register if needed) Create a new repository\nRepository Fill in repository info and click Create\nRepo Info Get an empty repository ready for blog code upload (note the git URL)\nEmpty Repo Download WordPress Download WordPress 4.9.4 from https://cn.wordpress.org/txt-download/ Extract files to get this structure:\nWordPress Execute these commands in the directory: git init git add -A git commit -m \u0026#39;first commit\u0026#39; ## Replace URL with your own git remote add origin https://git.coding.net/seth-shi/test.git git push -u origin master After pushing, enable dynamic page service:\nNavigate to your project \u0026gt; Code \u0026gt; Page Service \u0026gt; Dynamic Page \u0026gt; Enable\nDynamic Page Preview configurations (PHP7.1 support! Can set root directory - perfect for Laravel)\nConfig View MySQL connection info (needed later)\nMySQL Deploy master branch to get a subdomain\nBranch Access the domain to see WordPress installation page\nInstall Input database credentials from step 7 and click \u0026ldquo;Run Installation\u0026rdquo;\nSetup Complete registration and start blogging! For custom domains (requires premium membership).\nNote for Laravel projects: CODING doesn\u0026rsquo;t support composer yet. As confirmed by support, you need to push vendor directory manually (though they plan to add this feature later - awesome service!).\nSupport Chat ","date":"2018-03-26T17:33:16+08:00","image":"https://sethix.com/posts/2018032617/cover_hu2dbbece02abeab947c0cf536bf45a13c_7039_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018032617/","title":"Building a Blog for Free with CODING [Supports Dynamic Programs]"},{"content":"In daily processing of user operation events, we sometimes need to record them for future reference or big data statistics.\nLaravel handles model events conveniently: https://laravel-china.org/docs/laravel/5.5/eloquent#events\nThere are two approaches to Laravel model events:\nSet the dispatchesEvents property to map event classes Use observers to register events (this article focuses on the second approach) Implementation Steps Create Model\nphp artisan make:model Log \u0026lt;?php namespace App; use Illuminate\\Database\\Eloquent\\Model; class Log extends Model { protected $fillable = [\u0026#39;user_name\u0026#39;, \u0026#39;user_id\u0026#39;, \u0026#39;url\u0026#39;, \u0026#39;event\u0026#39;, \u0026#39;method\u0026#39;, \u0026#39;table\u0026#39;, \u0026#39;description\u0026#39;]; } Create Migration Table\nphp artisan make:migration create_logs_table\nTable structure example (customize as needed):\n\u0026lt;?php use Illuminate\\Support\\Facades\\Schema; use Illuminate\\Database\\Schema\\Blueprint; use Illuminate\\Database\\Migrations\\Migration; class CreateLogsTable extends Migration { public function up() { Schema::create(\u0026#39;logs\u0026#39;, function (Blueprint $table) { $table-\u0026gt;engine = \u0026#39;InnoDB\u0026#39;; $table-\u0026gt;increments(\u0026#39;id\u0026#39;); $table-\u0026gt;string(\u0026#39;user_id\u0026#39;)-\u0026gt;comment(\u0026#39;Operator\\\u0026#39;s ID\u0026#39;); $table-\u0026gt;string(\u0026#39;user_name\u0026#39;)-\u0026gt;comment(\u0026#39;Operator\\\u0026#39;s name for quick reference\u0026#39;); $table-\u0026gt;string(\u0026#39;url\u0026#39;)-\u0026gt;comment(\u0026#39;Current operation URL\u0026#39;); $table-\u0026gt;string(\u0026#39;method\u0026#39;)-\u0026gt;comment(\u0026#39;HTTP method of current operation\u0026#39;); $table-\u0026gt;string(\u0026#39;event\u0026#39;)-\u0026gt;comment(\u0026#39;Event type: create, update, delete\u0026#39;); $table-\u0026gt;string(\u0026#39;table\u0026#39;)-\u0026gt;comment(\u0026#39;Affected database table\u0026#39;); $table-\u0026gt;string(\u0026#39;description\u0026#39;)-\u0026gt;default(\u0026#39;\u0026#39;); $table-\u0026gt;timestamps(); }); DB::statement(\u0026#34;ALTER TABLE `logs` comment \u0026#39;Operation Log Table\u0026#39;\u0026#34;); } public function down() { Schema::dropIfExists(\u0026#39;logs\u0026#39;); } } Run Migration\nphp artisan migrate\nCreate Service Provider for Observers\nphp artisan make:provider ObserverLogServiceProvider\nRegister it in /config/app.php:\nproviders Create Base Observer Class\nCreate LogBaseServer under app/Observers:\n// Base class handles CLI execution scenarios LogBaseServer Implement Model Observer\nCreate observer for User model:\nUser Observer Register Observers\nIn ObserverLogServiceProvider:\nObserver Registration Bind Events to Models\nExample model event registration:\nModel Event Binding Trigger Events\nTest CRUD operations to populate logs:\nEvent Results Handling Many-to-Many Relationships Note: Methods like attach()/detach() don\u0026rsquo;t trigger model events. Bind Custom Event\nIn EventServiceProvider:\nprotected $listen = [ \u0026#39;App\\Events\\PermissionRoleEvent\u0026#39; =\u0026gt; [ \u0026#39;App\\Listeners\\PermissionRoleEventLog\u0026#39;, ], ]; Event Binding Create Event Class\nPermissionRoleEvent with parameters:\nPermissionRoleEvent Implement Listener\nPermissionRoleEventLog inherits LogBaseServer:\nListener Implementation Trigger Event\nEvent Trigger Handling Login/Logout Events Elegantly Bind Subscriber\nIn EventServiceProvider:\nprotected $subscribe = [ \u0026#39;App\\Listeners\\UserEventLog\u0026#39;, ]; Subscriber Binding Implement Event Methods\nIn UserEventLog:\nLogin/Logout Handlers Final Results\nDatabase Records END ","date":"2018-03-18T21:02:55+08:00","image":"https://sethix.com/posts/2018031821/cover_hu64e5e6bdf283a2972e837e08c447accf_4925_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018031821/","title":"Application of Laravel Model Events"},{"content":"This dream is a much older story that I felt compelled to write down due to its profound significance.\nIt began in a mortal village, a world of bustling markets and earthly concerns.\nWhile walking through the marketplace, celestial beings descended from the heavens - my first revelation that gods truly existed. When they announced the Heavenly Court needed recruits, I learned mortals could ascend to immortality.\nI still don\u0026rsquo;t know why I was chosen. Perhaps it was my desperate longing that made me surge forward faster than anyone else.\nThus I left the mortal realm for the Heavenly Palace, only to become a guardian of the Jade Emperor\u0026rsquo;s chambers. The work was mundane - opening doors at sunrise, closing them at moonrise. The tedium lasted until one moonlit night when I noticed another palace across the way. There sat a female immortal on the pavilion bench, who simultaneously became aware of my presence.\nWe spent nights gazing at each other until dawn\u0026rsquo;s first light forced me to hurriedly open the palace doors. Inquiries revealed this was the Queen Mother\u0026rsquo;s residence, though the female immortal\u0026rsquo;s identity remained unknown.\nOne fateful night after closing the doors, I gathered courage to approach her. Our eyes locked as I froze mid-step.\n\u0026ldquo;Did you also come from the mortal realm below?\u0026rdquo; Her question broke the tension. I stammered agreement, mentioning my loneliness. \u0026ldquo;You may sit,\u0026rdquo; she permitted, and I joined her on the bench.\nThat night I wished dawn would never come. But as sunlight returned, I glimpsed an ominous inscription on her palace pillar illuminated by the rays: \u0026ldquo;Do not fall in love with her! —Nine\u0026rdquo;. I dismissed it as some celestial prank.\nOur nightly conversations deepened until one moonlit meeting when she asked, \u0026ldquo;Do you miss home?\u0026rdquo; Seeing her wistful expression, I proposed: \u0026ldquo;Let\u0026rsquo;s visit the mortal world! If we return promptly\u0026hellip;\u0026rdquo;\nWe descended not just to my village, but wandered to seashores where we lay stargazing. I wished time could freeze\u0026hellip; until the harsh sunrise reminded me of our duty. Gripping her hand, we raced heavenward.\nWe arrived moments too late. The Jade Emperor and Queen Mother awaited with celestial soldiers. As spears pierced her heart, the Queen Mother declared: \u0026ldquo;Submit to punishment and live.\u0026rdquo;\nWhy hadn\u0026rsquo;t she spoken sooner? Rage consumed me. I seized the Queen Mother as hostage, retreating past celestial boundaries until encountering a colossal tree breaching Heaven\u0026rsquo;s walls - its trunk marked \u0026ldquo;Fourteen\u0026rdquo;.\nWith my love gone, I leapt into the void beyond the tree. The last thing I saw was that enigmatic \u0026ldquo;Fourteen\u0026rdquo; before weightless falling shocked me awake.\nKey translation considerations:\nMaintained mythological proper nouns using standard translations (Jade Emperor, Queen Mother) Preserved numerical symbols \u0026ldquo;Nine\u0026rdquo; and \u0026ldquo;Fourteen\u0026rdquo; as story-critical elements Converted date format to ISO standard Adjusted paragraph spacing to match original rhythm Kept Hugo front matter structure while translating fields Maintained poetic devices like repetition (\u0026ldquo;sunrise/moonrise\u0026rdquo;) and cosmic imagery Enhanced readability through natural English phrasing while preserving original narrative flow ","date":"2018-03-05T22:47:04+08:00","image":"https://sethix.com/posts/2018030522/cover_hu822567b9e81a5271ead9676244306880_115256_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018030522/","title":"The Story of Fourteen"},{"content":"I’m writing this down because of an unusual dream I had long ago. Tonight, while flipping through my notebook, I recalled this extraordinary vision.\nIn the dream, I was a slave laboring alongside others to build a pyramid. It seemed impossible that mere humans could construct such a marvel without assistance—in reality, people might speculate about alien intervention.\nBut in the dream, there were only shackled workers (perhaps prisoners would be a better term). Strangely, no one questioned why we were doing this.\nJust as I thought this routine would continue, I noticed something peculiar about the pyramid: each face had raised walkways flanking a smooth central surface, resembling water channels.\nThough the center appeared slick, slaves could walk on it. When I tried climbing halfway up, a bull suddenly charged down from the summit. Two ropes bound to it trailed into the raised channels on either side. As the beast galloped downward, the pyramid’s smooth surface began rising vertically. Workers scrambled to avoid being trampled.\nThe mechanical bull—now clearly visible as it neared me—was powering the entire pyramid’s movement. The ingenuity of human engineering left me awestruck.\nIronically, I didn’t dodge in time\u0026hellip; and then I woke up.\nWhy do I remember this? Because I always keep a notebook by my bed. Whenever a dream feels significant, I record it.\nNotebook Notebook ","date":"2018-03-02T21:18:09+08:00","image":"https://sethix.com/posts/2018030221/cover_hubbf3e022226683e136e0fbcb0dece78f_30543_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018030221/","title":"The Secret of the Pyramids"},{"content":"Here are some insights I’ve gained while working with Laravel to develop RESTful APIs.\nGetting Started API Authentication: For public APIs, consider OAuth2.0; for private/internal APIs, token-based authentication (e.g., JWT) is often sufficient. Versioning: Include an API version in routes for future scalability: Route::prefix(\u0026#39;v1\u0026#39;)-\u0026gt;group(function () { // Routes here }); CORS Handling: Use the barryvdh/laravel-cors package for seamless cross-origin requests. Sample API Endpoint\nExample Code Authentication Use jwt-auth for JWT-based authentication. Its 1.0+ version offers clear documentation. Unlike Laravel’s default token-based authentication (which uses an api_token field), JWT stores encrypted user data within the token itself. Security relies on keeping your JWT secret key (generated via php artisan jwt:secret) confidential. Routing Best Practices Use Route::apiResource() for RESTful resource routing (replaces 5 individual routes). Follow RESTful naming conventions: verbs, plural nouns, and clear semantics. For multi-word route segments, choose either hyphens (-) or underscores (_). Laravel uses hyphens by default. Learn more: Routing Conventions. Form Validation Prefer Form Request Classes over inline validation for cleaner controllers. Example: public function store(StoreUserRequest $request) { // Validated data is automatically available } Form Request Class Data Transformation Use Laravel’s Eloquent API Resources to format responses. Return single resources with UserResource and collections with UserResource::collection(). Conditionally include relationships using whenLoaded(): public function toArray($request) { return [ \u0026#39;id\u0026#39; =\u0026gt; $this-\u0026gt;id, \u0026#39;posts\u0026#39; =\u0026gt; PostResource::collection($this-\u0026gt;whenLoaded(\u0026#39;posts\u0026#39;)), ]; } API Resource Example Consistent Response Format Adopt a base controller to standardize API responses. Example structure:\nprotected function response($data, $status = 200) { return response()-\u0026gt;json([ \u0026#39;data\u0026#39; =\u0026gt; $data, \u0026#39;status\u0026#39; =\u0026gt; $status, ], $status); } Exception Handling Centralize exception handling in App\\Exceptions\\Handler:\npublic function render($request, Exception $exception) { if ($exception instanceof UnauthorizedHttpException) { return response()-\u0026gt;json([\u0026#39;error\u0026#39; =\u0026gt; \u0026#39;Invalid token\u0026#39;], 401); } if ($exception instanceof ValidationException) { return response()-\u0026gt;json([\u0026#39;errors\u0026#39; =\u0026gt; $exception-\u0026gt;errors()], 422); } if ($exception instanceof ModelNotFoundException) { return response()-\u0026gt;json([\u0026#39;error\u0026#39; =\u0026gt; \u0026#39;Resource not found\u0026#39;], 404); } return parent::render($request, $exception); } Exception Handling Simplify controller logic with findOrFail() or implicit model binding: public function show(User $user) { // Directly use $user } API Documentation Use Swagger UI + Swagger Editor for interactive documentation. Structure your OpenAPI spec in api.yaml/api.json and serve via Swagger UI.\nSwagger Setup Export specs from Swagger Editor and update your docs.\nSwagger Export Custom Package: laravel-api-helper I created a package to streamline common tasks:\nGenerate controllers and form requests via Artisan: php artisan api:auth Package Demo Features: Base controller inheritance, standardized responses, and validation shortcuts.\nLearn more: laravel-api-helper. Final Notes Prioritize clear documentation and consistent error handling. Keep controllers lean by delegating tasks to Form Requests, Resources, and dedicated classes. References RESTful API Design Guide Laravel API Development Best Practices ","date":"2018-03-01T22:06:16+08:00","image":"https://sethix.com/posts/2018030122/cover_hu2850c00dc50299f21f8afb7c73cc661b_19546_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018030122/","title":"Insights on Developing RESTful APIs with Laravel"},{"content":"When beginners learn PHP through tutorial videos, they often encounter the need to enable extensions like openssl and curl, which can be activated by simply modifying the php.ini file. However, installing extensions like redis and memcache requires finding the correct versions matching their PHP, NTS, VC, and Windows environment - a process that\u0026rsquo;s straightforward for experienced developers but challenging for newcomers.\nTo solve this problem, we\u0026rsquo;ve developed a one-click PHP extension installer program. The core workflow is as follows:\n+--------------+ +----------------+ +------------+ | open service | php install redis | down redis.dll | php index | show | | lamp/lnmp |------------------\u0026gt; | move redis.dll | ---------\u0026gt; | extensions | | environment | | update php.ini | | list | +--------------+ +----------------+ +------------+ Extensions are divided into two types:\nThose requiring DLL file downloads Those that can be enabled directly Extensions needing downloads are stored in the Extensions directory with a $mapUrl array containing key-value pairs:\nKey: Environment version Value: Extension package download URL Installation process:\nphp install redis detects the current environment version to construct the download URL Downloads and extracts the compressed package Copies DLL files to the PHP extensions directory Updates the php.ini configuration Usage examples:\n# Install redis extension php install redis # Install memcache extension php install memcache # View enabled extensions (restart server after installation) php index # Rollback php.ini configuration php install rollback Supported extensions and detailed instructions can be found in the Github documentation.\nDevelopers are welcome to contribute extension URLs and names to improve the program. If you find this tool helpful, please give it a ⭐ on GitHub!\nGitHub Repository\n","date":"2018-02-27T17:00:02+08:00","image":"https://sethix.com/posts/2018022717/cover_hu8f1341d5ff132883575c1275f28e88f8_4183_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018022717/","title":"One-Click PHP Extension Installer"},{"content":"If your imagejpg, imagepng, or imagegif functions can generate images but fail to display them in the browser, this article will help you resolve the issue.\nInitially, I compared a working file with the problematic one and found no visible differences - not even a single character.\nUndeterred, I downloaded a text comparison tool. The truth gradually emerged:\nText comparison tool As shown, the left (working) file uses standard UTF-8, while the right (problematic) file uses UTF-8 + BOM.\nKey differences between the encodings:\nUTF-8+BOM includes a three-byte prefix (0xEF 0xBB 0xBF) absent in standard UTF-8. While this prefix helps programs automatically detect UTF-8 encoding, it causes critical issues in PHP:\nThe extra three bytes trigger output before PHP\u0026rsquo;s header() function, violating its requirement of \u0026ldquo;no output before headers\u0026rdquo;. This prevents proper image rendering in browsers.\nSolution: Convert file encoding to standard UTF-8 (without BOM) using your code editor or IDE.\n","date":"2018-02-27T16:55:26+08:00","image":"https://sethix.com/posts/2018022716/cover_hu6164d6e2434c8799f2f12750a1345941_9329_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018022716/","title":"imagejpg-imagepng-imagegif Can Generate Images but Fail to Output to Browser"},{"content":"hello, world readme\nKey modifications made:\nKept English title unchanged Translated description to English Translated Chinese tags: 搭建 → setup, 博客 → blog Maintained technical terms: hugo/wordress/hexo/Github Adjusted timezone format to +08:00 Preserved code blocks and markdown syntax Maintained mixed-case spelling for \u0026ldquo;Github\u0026rdquo; (though technically should be \u0026ldquo;GitHub\u0026rdquo;) as per original ","date":"2018-02-27T14:46:56+08:00","image":"https://sethix.com/posts/2018022714/cover_hu34d1daa649511483d914d8b19de6f65e_5409_120x120_fill_box_smart1_3.png","permalink":"https://sethix.com/posts/2018022714/","title":"Hello, World!"}]