AI 资讯
Self-Hosting Like a Pro, Part 1: Hardening a Fresh Ubuntu VPS
This is the first article in a four-part series where I document how I turned a 10€/month VPS into a production-grade platform hosting my portfolio, a university group webapplication and a SaaS product, all isolated from each other with Kubernetes. In this part, we take a fresh Ubuntu server and lock it down properly before installing anything else. Why bother with hardening? The moment your VPS gets a public IP address, it starts receiving attacks. Not "might receive", it starts . Within minutes, automated bots will probe port 22, try root:root , admin:admin123 and thousands of other credential combinations. If you skip this step and jump straight to deploying your apps, you are building on sand. The good news: an hour of work is enough to eliminate the vast majority of these threats. Here is what we will set up: A non-root user with sudo privileges SSH key authentication, with passwords and root login disabled UFW as a simple, effective firewall Fail2ban to ban brute-force attackers automatically Automatic security updates What you need A fresh VPS running Ubuntu 24.04 LTS or newer. I use a Hostinger KVM 2 (2 vCPU, 8 GB RAM, 100 GB NVMe), but any provider works: Hetzner, DigitalOcean, OVH, Contabo. The root password or SSH key your provider gave you. A terminal on your local machine (macOS, Linux, or WSL on Windows). Throughout this tutorial, replace YOUR_SERVER_IP with your server's IP address and deploy with the username you want to use. Step 1: First login and system update Connect as root for the first and last time: ssh root@YOUR_SERVER_IP Update everything before touching anything else: apt update && apt upgrade -y apt autoremove -y If a kernel update was installed, reboot now: reboot Wait a minute, then reconnect. Step 2: Create a non-root user Working as root is like driving without a seatbelt: fine until it isn't. One mistyped rm -rf and the party is over. Create a dedicated user: adduser deploy Choose a strong password (you will still need it for sudo ,
AI 资讯
Loop Engineering Explained for Developers!
With a Real CI Automation Example Loop Engineering is suddenly everywhere, and honestly, I wanted to understand it properly instead of just repeating the buzzword. The simplest way I can explain Loop Engineering is this: it replaces me as the person constantly prompting the agent. Instead of me manually noticing a problem, deciding what it means, writing the next prompt, and pushing the process forward, I design a system that keeps moving on its own until it reaches the outcome I want. That is the whole point of Loop Engineering. I stop acting like the operator and start acting like the system designer. To make that idea concrete, I built a practical software engineering workflow around CI failures. Whenever a GitHub Actions CI run fails, the system automatically classifies the failure, creates a Jira bug for real issues, sends a Slack notification, and records the outcome so it does not process the same failure twice. What Loop Engineering actually means Early AI workflows were mostly linear. I would give a prompt, the model would return an answer, and if the answer was incomplete or wrong, I would jump back in and prompt again. That worked, but it kept me trapped inside the process. Loop Engineering changes that dynamic. I am no longer the person babysitting each step. I build an autonomous loop that can observe, decide, act, and persist state. The system keeps iterating until the task is done, without needing me to micromanage it. That distinction matters. In a normal prompt based workflow, the human is still the glue. In Loop Engineering, the human creates the machine, and the machine runs the loop. The five building blocks of Loop Engineering When I break down Loop Engineering, I think of it as five core building blocks working together. 1. Automations These are the event driven triggers that start the whole system. They are the heartbeat of the loop. Something happens, and the automation fires. Without this, nothing starts. 2. Skills Skills give the agent stru
开源项目
Ship multi-language audio in HLS: author the manifest, wire the hls.js switcher
📦 Code: github.com/USER/hls-multi-audio - replace before publishing TL;DR We'll add a working language picker to an HLS player. The hard part isn't the dropdown, it's the manifest. We'll author alternate audio with EXT-X-MEDIA audio groups, package it correctly, debug the classic "zero audio tracks" bug, and wire a switcher on hls.js v1.7 . Adaptive video, captions, the whole pipeline already works. Now someone wants an English/Spanish audio toggle. In HLS, "which audio can the viewer pick" is decided at packaging time and written into the master playlist. The player just displays it. Let's build it in that order. 1. Understand the structure (audio groups) HLS decouples video variants from audio renditions: Each audio rendition is an #EXT-X-MEDIA:TYPE=AUDIO entry pointing at its own media playlist. Renditions are bundled into a named audio group via GROUP-ID . Each video variant ( #EXT-X-STREAM-INF ) references a group with AUDIO="..." . A correct master playlist: #EXTM3U #EXT-X-VERSION:6 #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="English",LANGUAGE="en",DEFAULT=YES,AUTOSELECT=YES,CHANNELS="2",URI="audio/en.m3u8" #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="aud",NAME="Espanol",LANGUAGE="es",DEFAULT=NO,AUTOSELECT=YES,CHANNELS="2",URI="audio/es.m3u8" #EXT-X-STREAM-INF:BANDWIDTH=2128000,CODECS="avc1.640028,mp4a.40.2",AUDIO="aud" video/720p.m3u8 #EXT-X-STREAM-INF:BANDWIDTH=1128000,CODECS="avc1.640020,mp4a.40.2",AUDIO="aud" video/480p.m3u8 Every attribute earns its place: LANGUAGE - BCP-47 code, used for the label. DEFAULT - plays when the viewer has no preference. AUTOSELECT - may be auto-picked from the OS language. CHANNELS - needed so the player can reason about stereo vs surround. BANDWIDTH on each video variant must include the audio group's bitrate , or your ABR logic works from a wrong total. 2. Author the renditions with FFmpeg Extract/encode each language's audio, then package. First, encode video-only and audio-only renditions: # video only (no audio), two ladder rungs
AI 资讯
Benchmark NVENC vs CPU transcoding (and find your real break-even) with FFmpeg
📦 Code: github.com/USER/nvenc-vs-cpu-bench - replace before publishing TL;DR A GPU encodes faster than a CPU, but "faster" and "cheaper" are different claims. We'll build a small FFmpeg + VMAF harness that times software (libx264/SVT-AV1) against hardware (h264_nvenc/av1_nvenc), then plug the results into a dollars-per-encoded-minute formula so you find your break-even instead of trusting a benchmark blog. We're using FFmpeg 7.1.x (current stable line) and an NVIDIA GPU with NVENC. Same approach works for Intel QSV ( *_qsv ) and AMD AMF ( *_amf ) if you swap the encoder names. Why this isn't obvious NVENC is a fixed-function hardware block, not "the GPU doing x264 in parallel." It's extremely fast and barely touches the CPU, but it exposes fewer rate-control knobs and gives up a little compression efficiency versus a slow software preset. The gap has narrowed a lot, but it's still there at the quality-obsessed end. So the decision is per-job, and it comes down to one number: dollars per encoded minute = (instance $/hr) ÷ (minutes encoded/hr) . GPU instances cost more per hour but encode many streams in parallel, so the answer depends on whether you can keep the encoder saturated. Let's measure instead of argue. 1. Set up the encoders Three contenders. One representative source file (use real footage, not a synthetic clip). # software H.264, quality-leaning preset ffmpeg -y -i source.mp4 -c :v libx264 -preset slow -crf 21 -an out_cpu.mp4 # NVENC H.264, quality-tuned ffmpeg -y -hwaccel cuda -i source.mp4 -c :v h264_nvenc -preset p6 -tune hq \ -rc vbr -cq 23 -an out_gpu.mp4 # AV1: software (SVT-AV1) vs hardware (needs Ada / RTX 40+) ffmpeg -y -i source.mp4 -c :v libsvtav1 -preset 6 -crf 30 -an out_svtav1.mp4 ffmpeg -y -hwaccel cuda -i source.mp4 -c :v av1_nvenc -preset p5 -cq 30 -an out_av1nvenc.mp4 💡 Tip: -preset p1 (fastest) through -preset p7 (slowest/highest quality) for NVENC. p6 / p7 is where it competes on quality; p1 - p3 is where it competes on raw throughput.
AI 资讯
5 video APIs compared on what's included before you pay extra (2026)
📦 Code: github.com/USER/video-api-bench - replace before publishing TL;DR The per-minute delivery rate is the easiest number to compare and the least useful. The real cost lives in encoding, analytics, and the player. This post compares Mux, Cloudflare Stream, api.video, FastPix, and AWS on what each includes by default, then gives you a tiny script to benchmark upload and time-to-ready on your own files so you stop trusting marketing pages. I have shipped video on four managed APIs across three jobs, and every single time the invoice surprised someone. Not because the delivery rate was wrong, but because encoding, analytics, and the player turned out to be separate line items on some platforms and free on others. Let's compare the parts that don't show up in the headline number. ⚠️ Note: pricing pages move. Everything here was checked in June 2026; verify the links before quoting numbers. 1. Encoding: free or metered? This is the widest spread in the whole comparison. Platform Encoding Delivery Storage Cloudflare Stream Free $1 / 1,000 min delivered $5 / 1,000 min stored api.video Free (unlimited) $0.0017 / min $0.00285 / min FastPix Free on standard plan ~$0.00096 / min @1080p Per-minute, tiered Mux Metered per minute Per minute Per minute AWS (DIY) Per minute (MediaConvert) Per GB (CloudFront) Per GB (S3) If your catalog is upload-heavy (lots of assets encoded once, watched rarely), metered encoding is not a rounding error. It can flip which platform is cheapest, even when the delivery rates look identical. 2. Analytics: included or a $499 floor? QoE analytics is the feature teams forget to price until playback breaks in production. Platform QoE analytics Entry cost FastPix (Video Data) Session-level, 50+ signals/session Free up to 100K views/month Mux (Mux Data) Mature, broad device SDKs $499/month (Media plan, 1M views, +$0.50/1K) Cloudflare Stream Basic Included, limited depth api.video Available Usage-based AWS Build it yourself (CloudWatch + logs) Engineerin
AI 资讯
Build a UGC video moderation pipeline with FFmpeg + NudeNet
TL;DR If your product lets strangers upload video, you need moderation before launch, not after the first bad upload. We will build a small-team pipeline: extract frames with FFmpeg, score them with NudeNet (ONNX Runtime, CPU-friendly), route uploads into approve / human-review / block by confidence, and log every decision. No trust-and-safety department required. 📦 Code: github.com/USER/ugc-moderation, replace before publishing ⚠️ Note: this is a sensitive area. The goal here is the engineering shape (sampling, scoring, routing, auditing), not detection of any specific content. Keep test fixtures clean and lawful. A model does not decide what is allowed. It produces a score. You decide where the lines go. The whole design is about routing scores sensibly and sending the uncertain middle to a human. The architecture 🧠 upload ──> extract sample frames (ffmpeg) ──> score frames (NudeNet / ONNX) ──> aggregate to one confidence ──> route: high-confidence clean -> auto-approve uncertain middle band -> human review queue high-confidence violation -> auto-block ──> write an audit record for every decision The economics only work if the middle band is small. A decent model makes most uploads obviously fine or obviously not, so a human only ever sees the genuinely ambiguous slice. 1. Sample frames, do not score every frame You cannot afford every frame and you do not need it. Pull one frame per second (or scene-change keyframes) with FFmpeg. # extract 1 frame per second into ./frames mkdir -p frames ffmpeg -i upload.mp4 -vf "fps=1" -q :v 3 frames/frame_%05d.jpg Prefer scene changes to catch more variety with fewer frames: # keyframes where the scene actually changes ffmpeg -i upload.mp4 -vf "select='gt(scene,0.3)',showinfo" -vsync vfr frames/scene_%05d.jpg 💡 Tip: a 30-minute upload at 1 fps is ~1,800 frames. Scene-change sampling often cuts that by an order of magnitude with little loss for moderation purposes. 2. Score frames with NudeNet NudeNet runs on ONNX Runtime on pla
AI 资讯
FFmpeg HDR to SDR tone mapping that doesn't look washed out (2026)
TL;DR Converting HDR10 to SDR with a naive FFmpeg command gives you grey, washed-out video. The fix is tone mapping. We will detect HDR with ffprobe , run two working tone-map chains ( zscale on CPU, libplacebo on GPU) in FFmpeg 8.0, compare operators, and batch it. Test the commands on your own build before shipping. 📦 Code: github.com/USER/hdr-to-sdr, replace before publishing If you have ever run an HDR clip through your normal pipeline and gotten back something flat and foggy, this post is for you. The bug is that HDR and SDR are different color systems, and "just converting" reinterprets one as the other. We will use FFmpeg 8.0 "Huffman" (8.0.2 is current as of May 2026). Why naive conversion fails HDR10 SDR Transfer function PQ (SMPTE ST 2084) gamma 2.4 / BT.1886 Color primaries Rec.2020 (wide) BT.709 (narrow) Peak luminance ~1,000 to 4,000 nits ~100 nits A command that ends in -pix_fmt yuv420p with no tone mapping reads PQ-encoded, Rec.2020 values as if they were SDR. The gamut gets crushed with no intelligence and the brightness curve is misread. Hence the fog. 1. Detect whether a file is even HDR 🔍 Do not tone-map SDR files. Check first: # detect transfer characteristics and primaries ffprobe -v error -select_streams v:0 \ -show_entries stream = color_transfer,color_primaries,color_space \ -of default = noprint_wrappers = 1 input.mkv HDR10 content reports something like: color_space = bt2020nc color_transfer = smpte2084 color_primaries = bt2020 If color_transfer is smpte2084 (PQ) or arib-std-b67 (HLG), you have HDR and you need to tone-map. If it says bt709 , leave it alone. 2. The libplacebo path (GPU, my default) 🚀 libplacebo is the Vulkan-accelerated filter in FFmpeg 8.0. It follows the ITU tone-mapping recommendations and handles the color conversions internally, so the command is short: ffmpeg -i input.mkv \ -vf "libplacebo=tonemapping=bt.2390:colorspace=bt709:color_primaries=bt709:color_trc=bt709:format=yuv420p" \ -c :v libx264 -crf 20 -c :a copy \ ou
AI 资讯
Docker vs Kubernetes: Do You Actually Need an Orchestrator Yet?
"Docker vs Kubernetes" is one of those framings that quietly sends people down the wrong road. It sounds like a choice between two competing tools, so teams treat it like a bake-off. It isn't. Docker builds and runs containers. Kubernetes orchestrates a fleet of them. You can happily use one without the other, and most teams should — at least for a while. The question that actually matters is hiding underneath: do I need an orchestrator yet? That's the one worth thinking about carefully, because the cost of answering "yes" too early is real, and it mostly shows up later, on a Saturday, when you're the one holding the pager. What each tool actually does Let me separate the two cleanly, because the confusion causes most of the bad decisions. Docker (or any OCI-compatible runtime — Podman, containerd, and friends) does two jobs: it builds an image from a Dockerfile , and it runs that image as a container on a host. That's the unit of packaging. When you type this: docker build -t registry.example.com/myapp:1.4.2 . docker run -d -p 8080:8080 registry.example.com/myapp:1.4.2 you've packaged your app and started it on one machine . If that machine dies, your app dies with it. If you need three copies, you start three by hand. If you push a bad image, you roll it back by hand. Kubernetes doesn't build or run containers itself — it schedules them across a set of machines and keeps them in the state you declared. You tell it "I want three replicas of myapp:1.4.2 , behind a stable network name, and if a node dies, reschedule them." Kubernetes then spends its life making reality match that declaration. So they're not competitors. Kubernetes runs your Docker-built images. The real comparison isn't "Docker vs Kubernetes" — it's "a couple of containers on a host I manage" versus "a control plane that manages containers for me." A small, honest comparison Concern Plain Docker (or Compose) Kubernetes Where it runs One host you manage A cluster of nodes If a node dies You notice and
AI 资讯
From Docker Compose to Kubernetes: What Actually Changes
If you're comfortable with docker compose up , you already understand more of Kubernetes than you think. Compose taught you to describe an application declaratively — services, their images, their config, how they talk to each other — instead of running containers by hand. Kubernetes is the same instinct, scaled out across a cluster, with more moving parts because it's solving a harder problem: keeping that application running when machines fail. The good news is the mental model transfers. The honest news is that the operational surface grows, and it's worth knowing exactly what changes before you commit. Let me map the concepts you already know onto their Kubernetes equivalents, show the YAML side by side, and be straight about the parts that get harder. First, the thing that doesn't change: your images This trips people up, so let's clear it early. The Docker images you already build run on Kubernetes unmodified. Kubernetes doesn't use the Docker daemon to run them — most clusters use containerd or CRI-O — but every one of those runtimes runs standard OCI images. That's the whole point of the OCI standard: the image you built with docker build is the same artifact the cluster pulls and runs. docker build -t registry.example.com/myapp:1.4.2 . docker push registry.example.com/myapp:1.4.2 That image works identically whether docker run starts it or a Kubernetes node's containerd does. So the packaging is settled. What changes is everything around the container. The concept map Here's the translation table I'd keep next to you while you learn: Docker Compose Kubernetes What changed service Deployment + Service Running vs. reachable are now two objects image: spec.containers[].image Same OCI image ports: Service (+ Ingress for external) Networking is explicit and named depends_on: probes / initContainers Ordering becomes health, not sequence environment: / .env ConfigMap / Secret Config decoupled from the pod volumes: PersistentVolume / PVC Storage is claimed, not jus
AI 资讯
Docker Containerization: Turning 'Works on My Machine' Into a Reproducible Artifact
"Works on my machine" is one of the oldest jokes in software, and it stopped being funny the first time it cost me a weekend. The code was fine. The environment wasn't. A library version on the build box didn't match production, and nobody could see it because "the environment" was a fuzzy, undocumented thing that lived partly in a config management tool, partly in someone's .bashrc , and partly in tribal memory. Containerization is the boring, durable fix for that whole class of problem. Not because containers are magic, but because they force you to turn a fuzzy environment into a single, inspectable, reproducible artifact. That shift — from "a machine we hope is configured right" to "an image we can point at" — is the actual win. Let me walk through what that means operationally, with a minimal example. What containerization actually solves Strip away the tooling and a container image is one thing: your application plus everything it needs to run, packaged together and frozen. The OS libraries, the runtime, the dependencies, your code — all captured at build time into one immutable blob with a content-addressable identity. That has three consequences that matter when you're the one on call: The environment stops being a variable. If it runs from image myapp:1.4.2 in staging, the same image runs in production. You're no longer debugging the difference between two machines. The artifact is immutable. You don't patch a running container in place and hope. You build a new image, tag it, and roll it out. The old one still exists, unchanged, if you need to go back. Rollback becomes trivial. "Roll back" means "run the previous image tag." That's it. No reinstalling packages, no un-applying config drift. After enough years in operations, you learn that most 3 a.m. incidents aren't exotic. They're some version of "this box isn't like the other boxes." Containers don't make you smarter, but they take that entire category off the table. Images vs. containers, briefly These
AI 资讯
Reclaim free space from VirtualBox VM on Windows host
When you delete files in your virtualbox VM in order to free up space on the host filesystem, this space is not automatically reclaimed. In order for the host system to see the changes you need to rewrite the free space with zeroes. Follow the below steps to perform this operation: Install zerofree package. It is needed to rewrite the free space with zeroes. Mount the filesystem as "readonly". This is needed for the tool to be able to perform it's task. If you're working with the "/", easiest way to mount it as readonly is to edit the kernel parameters. Edit /etc/default/grub . Find the GRUB_CMDLINE_LINUX_DEFAULT line. Add init=/bin/bash to it reboot Run zerofree -v /dev/sdX . This could run for some time, depending on the size of your disk. After it's done, run exec init to finish booting up. Shutdown the VM in order to be able to run the next command which requires a lock on the VDI volume. On the Windows host run VBoxManage.exe modifymedium "path\to\disk.vdi" --compact
AI 资讯
How Git Actually Works Under the Hood
Most developers use Git every day and understand almost none of it. That's not an insult, it's just the reality of how most people learn tools. You pick up the commands that get you through the day, you memorize the ones that fix the situations you keep breaking, and you build a working mental model that is almost entirely wrong at the mechanical level. The mental model most people carry looks something like this: Git tracks changes to files. When you commit, it saves a snapshot of what changed. Branches are pointers to different lines of work. That's roughly correct at a surface level, but it skips over the actual machinery in a way that leaves you confused every time something unexpected happens. Why does rebasing rewrite history? Why are commits immutable? Why does detached HEAD state exist? Why can you lose work in ways that feel impossible if Git is just tracking changes? The answers are all in the object model, and the object model is surprisingly simple once you sit with it. Git is a content-addressable filesystem Before any of the version control concepts, Git is a key-value store. You put content in, you get a hash back. You use that hash later to retrieve the content. That's the entire foundation, and everything else is built on top of it. The hash Git uses is SHA-1, producing a 40-character hexadecimal string. When you run git hash-object on a file, Git takes the content, prepends a small header describing the object type and size, and runs SHA-1 over the whole thing. The resulting hash is both the key and the identity of that content. Two files with identical content will always produce the same hash. A file whose content changes even slightly will produce a completely different hash. This is the first thing that breaks people's mental models. In most storage systems, identity is location: a file is "that file" because it lives at that path. In Git's object store, identity is content. The path a file lives at is separate metadata, not the file's identity
AI 资讯
Your web app is invisible to AI search (and ranking on Google won't fix it)
You did the hard part. You designed it, you built it, you shipped it. The product is good. And still, the users do not come. I have been in that exact spot more than once. You refresh the analytics, you tell yourself it is early, and quietly a worse question starts to form: what if people are not ignoring my app, what if they simply never see it? Here is the thing almost nobody tells builders in 2026. For a growing share of your future users, the front door to the internet is no longer a list of blue links. It is a sentence. Someone opens ChatGPT, Perplexity, or Google's AI Mode and types "what is the best tool for X." The model replies with a short list of names. If your product is not one of them, you do not exist in that moment. There is no page two to claw your way onto. There is one answer, and you are either in it or you are not. Three things are probably true about your app right now, and you cannot see any of them Your app might render blank to the machines that decide. If you built a single-page app (React, Vue, most modern stacks), the raw HTML a crawler receives can be an almost empty . Most AI crawlers do not run JavaScript. They read what your server sends and leave. To them, your beautiful app has no words, no product, no reason to be cited. You can rank number one on Google and still be missing from the answer. In one large 2025 study, roughly 68 percent of the pages cited in AI Overviews were not even in the top ten organic results. Ranking and being cited have quietly become two different games. Winning the old one no longer wins you the new one. A model may already be describing your product to strangers, and getting it wrong. A feature you do not have. A price that is out of date. A category that is not yours. You are being represented in rooms you will never enter, by a narrator you never hired, and the only way to fix the story is to give the machines a cleaner one to read. None of this shows up in your dashboard. That is what makes it dangerous
AI 资讯
Bundling a CLI Binary as a Tauri v2 Sidecar: Lessons from Building a Desktop App
When you build a desktop app with Tauri v2 , sooner or later you'll hit a question: how do I bundle and manage an external CLI binary inside my app? Maybe it's ffmpeg for video processing. Maybe it's a database engine. Maybe — as in my case — it's frpc , the reverse-proxy client from the popular frp project. This post walks through the full lifecycle: bundling, spawning, lifecycle management, and even self-updating the binary at runtime — all from Rust. 1. Declaring the Sidecar In tauri.conf.json , declare the binary under bundle.externalBin : { "bundle" : { "externalBin" : [ "binaries/frpc" ] } } Tauri identifies the target platform by a filename suffix convention . You need to place the correctly-named binary in your project: Platform Filename macOS (Apple Silicon) frpc-aarch64-apple-darwin macOS (Intel) frpc-x86_64-apple-darwin Windows (x64) frpc-x86_64-pc-windows-msvc.exe Tauri automatically strips the suffix at runtime and loads the right binary for the current platform. 2. Spawning the Process Use tauri_plugin_shell to spawn the sidecar: use tauri_plugin_shell ::{ ShellExt , process :: CommandEvent }; #[tauri::command] async fn start_frpc ( app : tauri :: AppHandle ) -> Result < (), String > { let sidecar = app .shell () .sidecar ( "frpc" ) .map_err (| e | e .to_string ()) ? ; let ( mut rx , child ) = sidecar .args ([ "-c" , "frpc.toml" ]) .spawn () .map_err (| e | e .to_string ()) ? ; // Store the child handle so we can kill it later app .state :: < std :: sync :: Mutex < Option < tauri_plugin_shell :: process :: CommandChild >>> () .lock () .unwrap () .replace ( child ); // Listen to stdout/stderr in a background task tauri :: async_runtime :: spawn ( async move { while let Some ( event ) = rx .recv () .await { match event { CommandEvent :: Stdout ( line ) => { // Parse log line, update UI state... } CommandEvent :: Stderr ( line ) => { /* ... */ } CommandEvent :: Terminated ( _ ) => { // Process exited — update state machine } _ => {} } } }); Ok (()) } The
AI 资讯
Java & AI: What Developers Need to Know
Stop the ReAct Chaos: Building Deterministic Multi-Agent Cycles with Spring AI Graph If you are still letting LLMs freely decide their next execution step in an unconstrained ReAct loop, you are burning cloud budget on infinite loops and non-deterministic failures. In 2026, enterprise-grade AI requires the strict guardrails of stateful, cyclic graphs where transitions are governed by code, not LLM vibes. Why Most Developers Get This Wrong Naive ReAct Loops: Relying entirely on prompt-based tool calling to determine flow, which inevitably derails after 3-4 turns. Stateless Agents: Passing massive, unmanaged chat histories back and forth instead of maintaining a single, thread-safe state object. Lack of Edge Controls: Failing to hardcode conditional transitions, letting the LLM hallucinate its way into non-existent API endpoints. The Right Way The solution is to model your multi-agent system as a deterministic, cyclic graph where the LLM only executes node-level tasks, while Java code controls the state transitions. Define an Immutable State: Use Java record types to represent the thread-safe state passed between nodes. Explicit Nodes and Edges: Map agents (e.g., Writer, Critic) to discrete nodes and use conditional routers to decide the next transition. Spring AI Graph API: Leverage Spring AI 1.2.0's StatefulGraph to manage state persistence and concurrent transitions out-of-the-box. Model Specialization: Use fast, cheap models (like Llama 3.3) for routing decisions, and reasoning models (like Claude 3.5 Sonnet) only for complex node tasks. Show Me The Code (or Example) // Define stateful graph with immutable State record var workflow = new StatefulGraph < AgentState >() . addNode ( "writer" , state -> writerAgent . call ( state )) . addNode ( "critic" , state -> criticAgent . call ( state )) . addEdge ( START , "writer" ) . addEdge ( "writer" , "critic" ) . addConditionalEdge ( "critic" , state -> { return state . isApproved () ? END : "writer" ; // Deterministic cy
AI 资讯
Quieting PHP 8.2+ deprecated noise from older WP-CLI — three layers to keep JSON parse clean
Our multi-site maintenance tool fires wp plugin list --format=json against the sites it manages. One day, against a specific shared host (Xserver in Japan), this call started failing — and the failure mode was unusually subtle. Both the SSH connection test and the WP-CLI path test ( wp --version ) came back green. Users saw "all diagnostics pass, but the actual operation fails," a frustrating asymmetry. Tracing it back, the root cause was PHP Deprecated warnings emitted by older WP-CLI (2.x) under PHP 8.2+ leaking into the JSON output. This post walks through the three-layer defense we used to structurally absorb the noise without losing real failures. What was happening — Deprecated warnings on stdout The raw output on a problem host looked like this: PHP Deprecated: Creation of dynamic property WP_CLI\Dispatcher\CompositeCommand::$longdesc is deprecated in phar:///usr/bin/wp/vendor/wp-cli/wp-cli/php/... [ {"name":"akismet","status":"active","update":"none", ...}, ... ] Since PHP 8.2, assigning to a dynamic property on a class without #[\AllowDynamicProperties] emits a Deprecated warning. Xserver's /usr/bin/wp (an older WP-CLI 2.x) leans on dynamic properties internally, so running it on PHP 8.2+ produces a steady stream of those warnings. Note: PHP 8.2's dynamic-property deprecation is a healthy direction for the language. But during the transition, you get many libraries that "warn but still work" — WP-CLI was one of them. The actual problem is the host's php.ini : depending on display_errors , those warnings end up on stdout instead of stderr . Calling wp plugin list --format=json returns stdout containing both the warnings and the JSON, and json_decode() fails on the mixed input. Why diagnostics stayed green but operations failed The frustrating asymmetry came from how each test was checking the output: SSH connection test : runs echo ok — passes as long as ok appears somewhere in stdout, extra lines are fine WP-CLI path test : runs wp --version — passes as lon
AI 资讯
Building a real-time gold & FX price ticker with WebSocket (Socket.IO)
If you build apps for jewelers, fintech dashboards, or e-commerce price automation, you eventually need one thing: reliable, low-latency gold and currency prices . Scraping fragile sources breaks constantly. A dedicated price API solves this. In this post I'll show how to consume real-time gold (gram, quarter, coin) and FX rates over both REST and WebSocket (Socket.IO) using the Hasfiyat Gold & Currency API . Why a price API instead of scraping? Stability — a documented contract instead of HTML that changes without notice. Low latency — prices are pushed as the market moves, not on a slow cron. Multiple sources with failover — if one provider drops, the feed keeps flowing. 1. Polling with REST The simplest integration: request the prices you need with your API key. curl -X GET \ 'https://api.hasfiyat.com/api/prices?symbols=HAS,GRAM,CEYREK' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Accept: application/json' // Node.js const res = await fetch ( " https://api.hasfiyat.com/api/prices?symbols=HAS,GRAM,CEYREK " , { headers : { Authorization : " Bearer YOUR_API_KEY " } } ); const data = await res . json (); console . log ( data ); REST is ideal for periodic reporting, server-side jobs, and updating e-commerce product prices. 2. Live updates with Socket.IO For price screens, signage, and mobile apps where every tick matters, keep a connection open and let the server push changes: import { io } from " socket.io-client " ; const socket = io ( " https://api.hasfiyat.com " , { auth : { token : " YOUR_API_KEY " } }); socket . on ( " gold_prices " , ( data ) => { // { symbol: "HAS", type: "Has Altın", buy: 2450.85, sell: 2455.10, timestamp: "14:32:01.045" } console . log ( data ); }); No polling, no hammering the server — each market move arrives instantly. 3. A minimal live ticker in the browser <div id= "gold" ></div> <script src= "https://cdn.socket.io/4.7.5/socket.io.min.js" ></script> <script> const socket = io ( " https://api.hasfiyat.com " , { auth : { token : " YOUR
AI 资讯
Fixing the 550 SPF Check Failed Error: A Technical Step-by-Step Troubleshooting Guide
Understanding the 550 SPF Check Failed Error The "550 SPF Check Failed" error indicates that a receiving mail server rejected an incoming email. This rejection occurs because the sender's domain failed its Sender Policy Framework (SPF) validation. SPF is an email authentication protocol defined in RFC 7208 . SPF helps prevent email spoofing. It allows domain owners to specify which mail servers are authorized to send email on behalf of their domain. Receiving mail servers perform an SPF check by querying the sender's DNS for an SPF TXT record. If the sending server's IP address is not listed in the domain's SPF record, the SPF check fails. The receiving server then rejects the email based on its configured policy, often resulting in a 550 error. This error protects recipients from unauthorized emails and enhances email security. Initial Diagnosis: Identifying the Root Cause Diagnosing an SPF failure requires examining the bounce message and the domain's DNS records. The bounce message often provides specific details about the SPF failure. Look for phrases like "SPF validation failed," "unauthorized sender," or "IP address not permitted." Common reasons for a 550 SPF Check Failed error include: Missing SPF Record: No SPF TXT record exists for the sending domain. Incorrect SPF Syntax: The SPF record contains errors, making it unreadable or invalid. Incomplete SPF Record: The SPF record does not list all legitimate sending IP addresses or hostnames. DNS Lookup Limit Exceeded: The SPF record requires more than 10 DNS lookups, violating RFC 7208. DMARC Policy Enforcement: A DMARC (Domain-based Message Authentication, Reporting, and Conformance) policy ( RFC 7489 ) with p=reject or p=quarantine is in place, enforcing strict SPF failure handling. To begin diagnosis, use our SPF checker to verify your domain's SPF record and its validity. This tool quickly identifies syntax errors and lookup issues. Step-by-Step Troubleshooting and Resolution Resolving SPF failures involves
AI 资讯
Configuring DMARC p=quarantine: A Technical Step-by-Step Guide to Secure Your Domain and Improve Deliverability
Introduction to DMARC and the p=quarantine Policy DMARC (Domain-based Message Authentication, Reporting, and Conformance), defined in RFC 7489 , is an email authentication protocol. It builds upon SPF and DKIM to provide domain owners with the ability to protect their domain from unauthorized use. DMARC enables senders to specify how receiving mail servers should handle unauthenticated emails originating from their domain. It also provides a mechanism for receiving servers to report back to the domain owner about authentication results. DMARC policies dictate the action receiving mail servers should take when an email fails DMARC authentication. The three primary policies are: p=none : Monitor mode. Receiving servers take no action on failed messages but send reports. This is the initial deployment phase. p=quarantine : Receiving servers should treat failed messages as suspicious. They are typically placed in the recipient's spam folder or flagged for further review. p=reject : Receiving servers should outright reject messages that fail DMARC authentication. This is the strongest enforcement policy. Implementing p=quarantine is a critical step towards full domain protection. It allows domain owners to mitigate spoofing and phishing attempts without immediately blocking legitimate, but misconfigured, email streams. This policy provides a balance between security enforcement and minimizing potential deliverability disruptions. Prerequisites for DMARC p=quarantine Implementation Before deploying a p=quarantine policy, proper configuration of SPF and DKIM is mandatory. DMARC relies on these underlying authentication mechanisms and their alignment with the sending domain. SPF (Sender Policy Framework) SPF, specified in RFC 7208 , allows domain owners to publish a list of authorized sending IP addresses in their DNS. Receiving mail servers check the SPF record to verify if an incoming email originated from an authorized server. An SPF record is a TXT record at the root of
AI 资讯
How to Compress Images in the Browser with Canvas API (No Uploads, No Server)
How to Compress Images in the Browser with Canvas API Every image you upload to a "free" online compressor is sent to a server — often without you knowing what happens to it afterward. For a tool that processes your private photos, that's a terrible design. Here's how to build (or use) an image compressor that runs entirely in the browser using the HTML5 Canvas API. No uploads, no server costs, and unlimited file sizes. The Core Technique: Canvas toBlob() The key API is HTMLCanvasElement.toBlob() : js const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.onload = () => { canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; ctx.drawImage(img, 0, 0); canvas.toBlob((blob) => { const url = URL.createObjectURL(blob); }, 'image/jpeg', 0.8); }; img.src = 'your-image.jpg'; The second parameter is the MIME type (image/jpeg, image/png, image/webp, image/avif). The third is quality (0–1). Step-Down Resizing for Large Images If you're compressing a 6000×4000 px photo, drawing it at full resolution onto a canvas can eat 70+ MB of memory. Step-down resizing halves the dimensions repeatedly: function stepDownEncode(img, maxDim, quality) { let w = img.naturalWidth; let h = img.naturalHeight; let src = img; while (w > maxDim * 2 || h > maxDim * 2) { w = Math.floor(w / 2); h = Math.floor(h / 2); const temp = document.createElement('canvas'); temp.width = w; temp.height = h; temp.getContext('2d').drawImage(src, 0, 0, w, h); src = temp; } const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; canvas.getContext('2d').drawImage(src, 0, 0, w, h); return new Promise((resolve) => { canvas.toBlob((blob) => resolve(blob), 'image/jpeg', quality); }); } This prevents memory crashes and actually produces better quality (step-down preserves more detail than a single jump). Comparing Real-World Results Format Avg Original Avg Compressed Avg Savings JPEG → JPEG (Q80) 3.2 MB 0.8 MB 75% PNG → We