AI 资讯
I Built a RAG Pipeline in TypeScript Without LangChain — The Whole Thing in 200 Lines
Every RAG tutorial I found looked like this: const chain = RetrievalQAChain . fromLLM ( model , vectorStore . asRetriever ()); const res = await chain . call ({ query : " what is this document about? " }); Twelve lines, a Pinecone key, a screenshot of it answering one question about one PDF, and a confident closing paragraph about "production readiness." I read four of them and still couldn't have told you what an embedding actually was, why cosine similarity was the metric everyone used, or what would happen if my documents were 800 pages instead of 8. I could copy the code. I couldn't debug it. So I deleted the frameworks and wrote the whole thing by hand. No LangChain, no LlamaIndex, no hosted vector database, and no cloud LLM — the model runs on my laptop. Six files, a bit over 200 lines of TypeScript, and nothing imported that I can't explain. This post is the whole pipeline, the data structures behind each stage and why they were chosen, the four bugs that cost me the most time, and a debugging method that will save you an afternoon. Who this is for I'm assuming you write JavaScript or TypeScript, you're comfortable with async / await , arrays, and classes, and you've installed an npm package before. That's it. I am not assuming you know anything about machine learning, vectors, embeddings, or information retrieval. Every one of those is explained from zero as it comes up, and if a line of code does something non-obvious, I explain the line. If you already know what a vector store is, skip to the bug list at the bottom. What RAG actually is Strip the acronym away and RAG is one idea: Language models can't read your files. So find the relevant paragraphs yourself, paste them into the prompt, and ask the question. The rest of the pipeline exists to make that sentence practical. Finding the right paragraphs is the hard part. You can't keyword-search your way there, because a user asking "how do I stop duplicate rows" won't use the word "DISTINCT" that appears in
AI 资讯
Building a Restaurant Reservation System with Node.js, Express & MongoDB - A Beginner's Guide
Building a Restaurant Reservation System with Node.js, Express & MongoDB - A Beginner's Guide Tags: #nodejs #express #mongodb #webdevelopment #tutorial #beginner Introduction Hey everyone! 👋 This is my first Dev.to post, and I'm excited to share what I've been learning. As a 5th-semester CS student, I've been diving deep into full-stack web development, and today I want to walk you through building a Restaurant Reservation System – a real project I built that taught me so much about backend architecture and database design. If you're just starting with Node.js, Express, and MongoDB, this post is for you! What We'll Build A simple but functional restaurant reservation system where: Users can browse available time slots Users can book a table for a specific date and time Admin can manage reservations Weekly scheduling (Monday-Sunday) 2-hour time slots Tech Stack: Backend: Node.js + Express Database: MongoDB Frontend: React + Tailwind CSS (we'll focus on backend in this post) Prerequisites Before we start, make sure you have: Node.js installed MongoDB running locally or MongoDB Atlas account Basic JavaScript knowledge VS Code or any code editor Project Setup 1. Initialize the Project mkdir restaurant-reservation-system cd restaurant-reservation-system npm init -y 2. Install Dependencies npm install express mongoose cors dotenv npm install nodemon --save-dev 3. Create Project Structure restaurant-reservation-system/ ├── models/ │ └── Reservation.js ├── routes/ │ └── reservations.js ├── config/ │ └── db.js ├── .env ├── server.js └── package.json Step 1: Set Up MongoDB Connection config/db.js const mongoose = require ( ' mongoose ' ); const connectDB = async () => { try { await mongoose . connect ( process . env . MONGODB_URI ); console . log ( ' MongoDB connected successfully ' ); } catch ( error ) { console . log ( ' MongoDB connection failed: ' , error ); process . exit ( 1 ); } }; module . exports = connectDB ; Step 2: Create Reservation Model models/Reservation.js co
AI 资讯
Environment Variables the Safe Way
Why Environment Variables Matter Every app has secrets: API keys, database URLs, admin passwords. Hardcoding them in source code is a one-way ticket to leaks. Even if your repo is private, you never know who forks it or what CI logs expose. Environment variables are the standard way to keep configuration out of code. But using them safely requires a few habits that go beyond just process.env . The Basics: Loading and Accessing In Node.js, you read env vars with process.env . But you should not access them raw everywhere. Create a central config module that validates and exposes them. // config.js const required = [ ' DB_URL ' , ' API_KEY ' , ' PORT ' ]; for ( const key of required ) { if ( ! process . env [ key ]) { throw new Error ( `Missing required env var: ${ key } ` ); } } module . exports = { dbUrl : process . env . DB_URL , apiKey : process . env . API_KEY , port : parseInt ( process . env . PORT , 10 ), }; Fail fast at startup. If a required variable is missing, crash immediately rather than failing later in a confusing way. Never Commit .env Files Tools like dotenv load variables from a .env file for local development. That file must stay out of version control. Add .env to your .gitignore immediately. Also add .env.local , .env.production , etc. if you use them. Instead of committing the actual values, commit a .env.example with placeholder or fake values. This documents what is needed without exposing anything. # .env.example DB_URL = postgres :// user : password @ localhost : 5432 / mydb API_KEY = your - api - key - here PORT = 3000 Use a Validation Library Manual checks are fine for small projects, but for anything serious use a schema validator like envalid or joi . They give you type coercion, defaults, and clear error messages. // with envalid const { cleanEnv , str , num } = require ( ' envalid ' ); const env = cleanEnv ( process . env , { DB_URL : str (), API_KEY : str (), PORT : num ({ default : 3000 }), }); module . exports = env ; This catches m
AI 资讯
npm 12 Released: Install Scripts Off by Default as Registry Moves to Explicit Trust
npm 12 introduces significant security-related changes, making certain installation behaviors opt-in. Notably, script allowances are now off by default, which requires explicit approval for running scripts, including implicit builds. The update also restricts non-registry sources and addresses community concerns about security risks from automatic script execution. By Daniel Curtis
AI 资讯
Add Model Fallback to an OpenAI-Compatible Node.js App
A single model can be unavailable, rate-limited, or temporarily slow. If your application already uses an OpenAI-compatible API, a simple fallback can make testing more resilient without introducing another SDK. This tutorial uses Node.js and the official OpenAI JavaScript package. It tries one model first and switches to a second model only when the first request fails. 1. Install the SDK npm install openai 2. Store the API key outside your code On macOS or Linux: export JINZEAI_API_KEY = "your_api_key_here" On PowerShell: $ env : JINZEAI_API_KEY = "your_api_key_here" Never commit a real API key. Rotate it immediately if it appears in a public repository, screenshot, or support message. 3. Create an OpenAI-compatible client import OpenAI from " openai " ; const client = new OpenAI ({ baseURL : " https://jinzeai.cc/v1 " , apiKey : process . env . JINZEAI_API_KEY , }); 4. Add a small fallback function const models = [ " deepseek-chat " , " qwen-flash " ]; async function completeWithFallback ( messages ) { let lastError ; for ( const model of models ) { try { const response = await client . chat . completions . create ({ model , messages , }); return { model , text : response . choices [ 0 ]. message . content , }; } catch ( error ) { lastError = error ; console . warn ( ` ${ model } failed: ${ error . status ?? " unknown status " } ` ); } } throw lastError ; } const result = await completeWithFallback ([ { role : " user " , content : " Explain model fallback in one sentence. " , }, ]); console . log ( `Model: ${ result . model } ` ); console . log ( result . text ); 5. Decide which errors should trigger fallback The minimal example retries on every error so the control flow is easy to see. A production application should be more selective. Fallback may be reasonable for: rate limits; upstream server errors; temporary timeouts; a model that is unavailable to the current account. Do not silently retry authentication errors. An HTTP 401 usually means the key is missing,
AI 资讯
Support Catalog Backfill: Moderate Existing Posts and Comments in a Node.js Bulk Job
Per-tenant cost visibility changes the design: don't begin with parallel API calls; begin with a durable ledger that ties every classification result and usage record to a tenant, policy version, and source item. For a customer-support catalog backfill, the practical choice is a bounded Node.js worker that reads existing posts and comments, classifies them through a replaceable adapter, checkpoints each result, and exports tenant-scoped JSONL. Short answer: make the ledger the product of the job and the LLM call one restartable step inside it. That ordering matters when support conversations contain messy product descriptions such as “the small blue charger for the old tablet.” The moderation label decides whether the text is safe to reuse; the enrichment labels connect it to a catalog candidate. Operations still need to answer a less glamorous question: which tenant consumed the tokens? Make tenant cost visible before optimizing it Token totals belong beside decisions, not in an unrelated monthly dashboard. Record normalized input and output token counts on every completed row, then aggregate by tenantId , policyVersion , and time window. If the API reports different usage units, preserve the raw usage payload in restricted telemetry and map it explicitly; don't pretend unlike units are interchangeable. Start there. Three signals are enough for the first useful view: Signal Group by Operational question Completed items tenant, policy version Is the backfill moving? Input and output tokens tenant, model Where is consumption occurring? Review and block counts tenant, content kind Did the decision mix shift? Cost in currency should be derived from a versioned rate configuration, not baked into historical rows. Store usage and the model identifier, then apply the applicable rate when producing a report. This keeps a rate change from rewriting what the runtime actually observed. It also lets finance reproduce an invoice-period view while engineering inspects tokens per
AI 资讯
Upload Moderation: Node.js NSFW, Violence, Hate-Symbol Classification + JSON Fallback
Short answer: for media support tickets that include an image, keep classification, policy enforcement, and tenant cost accounting as three separate steps. Send the image to a multimodal chat model with a strict JSON Schema, validate the returned object locally, and send invalid or uncertain cases to review. The fallback is a queue, not a guess. That design matters because a support agent is usually triaging a complaint, not publishing a photo. The same upload might be evidence of a violent broadcast, a screenshot containing a hate symbol, or an ordinary account avatar. A boolean called safe throws away the context that the agent needs. Keep it boring. How can a Node.js image moderation flow classify risky uploads without trusting JSON? Start with a versioned taxonomy. For this media workflow, I would keep nsfw , violence , and hate_symbols as separate observations, add uncertain , and retain a short evidence string. The model describes what it can see; application code decides whether a ticket is visible, blocked, or waiting for a human. This boundary also makes an eval harness useful: a prompt change can be tested independently from the enforcement policy. The tempting shortcut is to ask for a sentence and search it for words. It feels flexible in a notebook, then becomes difficult to replay: punctuation changes the parser, a missing category looks like a negative result, and a tenant's policy cannot be reconstructed from a free-form answer. Typed output is not a safety decision, but it gives the rest of the pipeline a stable input. Here is a deliberately small adapter. The surrounding Node.js upload service can call the same contract from any language; the example keeps the model call behind an OpenAI-compatible chat client and uses environment variables for the concrete base URL and model. It does not publish an upload merely because the response parses. import json import os from openai import OpenAI MODERATION_SCHEMA = { " name " : " media_upload_labels " , "
AI 资讯
5 Advanced CLI Engineering Patterns in Node.js & Go (Building Production Tools)
5 Advanced CLI Engineering Patterns in Node.js & Go (Building Production Tools) Command line utilities (CLIs) are the backbone of modern developer workflows. From package managers to security scanners, a well-engineered CLI tool can boost developer velocity tenfold. Drawing from production patterns behind open-source CLI tools like node-reaper and port-sniper , here are 5 essential engineering patterns for building high-performance CLI utilities. 1. Graceful Process Signal Handling (SIGINT / SIGTERM) Always handle Ctrl+C cleanly to release ports, clean up temporary files, and restore cursor states. 🔴 Node.js Signal Handler Pattern: import process from ' node:process ' ; function setupGracefulShutdown ( cleanupFn : () => Promise < void > ) { const shutdown = async ( signal : string ) => { console . log ( `\n\n[INFO] Received ${ signal } . Cleaning up resources...` ); try { await cleanupFn (); console . log ( " [SUCCESS] Cleanup complete. Exiting. " ); process . exit ( 0 ); } catch ( err ) { console . error ( " [ERROR] Cleanup failed: " , err ); process . exit ( 1 ); } }; process . on ( ' SIGINT ' , () => shutdown ( ' SIGINT ' )); process . on ( ' SIGTERM ' , () => shutdown ( ' SIGTERM ' )); } 2. Interactive Terminal Prompts & Selection Instead of forcing users to memorize complex flags, provide interactive dropdown menus when flags are omitted. 🔴 Interactive Dropdown Selection: import { select } from ' @inquirer/prompts ' ; export async function promptTargetSelection ( processList : { pid : number ; port : number ; name : string }[]) { const selectedPid = await select ({ message : ' Select zombie process to kill: ' , choices : processList . map ( proc => ({ name : `Port ${ proc . port } ──► PID ${ proc . pid } ( ${ proc . name } )` , value : proc . pid , })), }); return selectedPid ; } 3. High-Speed Concurrent Task Execution in Go When scanning filesystem directories (e.g. cleaning node_modules ), use Go goroutines with worker pools for maximum IOPS efficiency. packa
开发者
Why I Chose NestJS and Never Looked Back
A few years ago, I was just another developer trying to figure out how to build things that actually work, not just things that run once and fall apart the moment real users touch them. I tried a few paths. I read a lot. I broke a lot of things. And somewhere along that road, I found NestJS. At first, it looked like just another tool. Another framework to learn, another thing to add to my resume. But the more I used it, the more I realized something. NestJS wasn't just teaching me how to build backend systems. It was teaching me how to think like someone who builds things meant to last. I did not choose NestJS because it was trendy. I chose it because it made me feel organized in a way nothing else had. It gave structure to ideas that used to feel messy in my head. It made me feel like a professional, not just someone typing code and hoping it works. Here is the lesson I want you to take from this, even if you never write a single line of NestJS code. Anything you build, whether it is software, a business, or even your own life, lasts longer when it has structure. Not rules for the sake of rules, but structure that makes room for growth without everything falling apart. That is what NestJS taught me first, before it taught me anything technical. Organize your thinking, and the work becomes easier to carry. Today, when people ask me why I still use NestJS after all this time, my answer is simple. It is not just a tool I use. It is the reason I became confident in what I do. And once you experience that kind of confidence in your work, it is very hard to walk away from it. I write these thoughts as Peace Melodi, a backend software engineer who cares deeply about building things that hold up under real pressure, real users, and real growth. If any of this resonated with you, I would love to connect. LinkedIn: https://www.linkedin.com/in/melodi-peace-406494368 GitHub: https://github.com/PeaceMelodi
AI 资讯
Your ORM is hiding the line that caused the slow query
I was building a runtime N+1 query detector for Node. The detection part worked on the first afternoon. Getting it to tell you which line of your code caused the problem took considerably longer, and taught me something about how ORMs execute queries that I had not thought about before. This is that story, and the fix. The symptom The detector instruments your database driver. When the same query shape runs many times inside one request, it reports it — along with the file and line that issued it, which is the part that actually saves you time: nplusone 1 finding in GET /orders — 51 queries, 840ms N+1 query 50× SELECT * FROM items WHERE order_id = ? at src/routes/orders.ts:47:38 (loadOrdersPage) 612ms spent here That worked. Then I pointed it at an app using Drizzle and got this instead: N + 1 query 12 × select "id" , "order_id" from "items" where "items" . "order_id" = $ 1 < unknown call site > Detected, counted, and attributed to nothing. Do not theorise. Dump the stack My first instinct was that my frame filter was too aggressive — it skips node_modules , node:internal , and the library's own frames, so maybe it was eating something it should not have. Rather than guess, I printed the whole stack at the exact moment the driver was called: const originalQuery = pg . Client . prototype . query ; pg . Client . prototype . query = function (... args ) { const previous = Error . stackTraceLimit ; Error . stackTraceLimit = 100 ; const stack = new Error (). stack . split ( " \n " ). slice ( 1 ); Error . stackTraceLimit = previous ; console . log ( " FRAMES: " , stack . length ); stack . forEach (( line , i ) => { const mine = ! /node_modules|node:internal/ . test ( line ); console . log ( ` ${ String ( i ). padStart ( 3 )} ${ mine ? " >>> " : " " } ${ line . trim ()} ` ); }); return originalQuery . apply ( this , args ); }; Here is what came back for a single await db.select().from(items).where(...) : FRAMES: 12 0 at Proxy.<anonymous> (.../nplusone/dist/adapters/postgre
AI 资讯
How I Protected My Express API from Spam and High AI Costs Using Redis
When I was building my backend API, I realized a big problem: anyone could spam my endpoints. If a user repeatedly reloads a page or hits an endpoint calling an external AI service, it can crash the server or run up high API costs. To fix this, I added Rate Limiting . Here is why I used Redis for it and how I set it up. The Problem with Simple In-Memory Limiters At first, I thought about saving request counts in a simple JavaScript object: // ❌ Simple in-memory check (Not good for production) const requestCounts = {}; app . use (( req , res , next ) => { const ip = req . ip ; requestCounts [ ip ] = ( requestCounts [ ip ] || 0 ) + 1 ; if ( requestCounts [ ip ] > 100 ) { return res . status ( 429 ). json ({ error : " Too many requests " }); } next (); }); This works locally, but has two big flaws: 1)Memory Leaks: The requestCounts object keeps growing in memory forever. 2)Breaks when Scaling: If you deploy multiple instances of your app behind a load balancer, each server keeps its own count. A user can easily bypass the limit by hitting different servers. The Solution: Centralized Redis Store Redis stores data in RAM outside our Node.js app. Because it is centralized, all server instances share the exact same count. [ Incoming Client Requests ] │ ▼ [ Cloud Load Balancer ] │ ┌───────────────┼───────────────┐ ▼ ▼ ▼ [ Express Node 1 ] [ Express Node 2 ] [ Express Node 3 ] │ │ │ └───────────────┼───────────────┘ ▼ [ Central Redis Store ] (Checks Request Limits) How I Configured It in My Project In my app, I use two levels of protection: Global Limit: 100 requests per 15 minutes for normal routes. Strict Limit: 5 requests per 10 minutes for heavy routes (like AI generation or OTP emails). 1 . Redis Connection ( config / redis . js ) import { createClient } from ' redis ' ; const redisClient = createClient ({ url : process . env . REDIS_URL || ' redis://localhost:6379 ' }); redisClient . on ( ' error ' , ( err ) => console . error ( ' Redis Error: ' , err )); redisClient .
AI 资讯
CPU utilization lies: autoscaling a single-threaded service
The service was slow. Not down, just slow: p95 latency climbing well past where users notice, requests piling up, the kind of degradation that generates support tickets instead of alerts. And the autoscaler, the whole point of which is to add capacity when a service is under strain, sat there doing nothing. The metric it was watching said everything was fine. Average CPU utilization on the tasks was hovering around 30 percent, nowhere near the scale-out threshold. The dashboard was calm. The users were not. Both were right, and the gap between them is one of the most common autoscaling traps on a container platform. This is the first article in a series on running a multi-tenant SaaS on AWS at team scale. It is about a metric that lies, quietly, by design. Why 30 percent CPU meant 100 percent busy The service was a single-threaded application. A Node.js API, in this case, but the same is true of any process that does its real work on one thread: a classic Python or Ruby worker, most single-process runtimes. A single-threaded process can, by definition, saturate exactly one CPU core. The task it was running on had four vCPUs. So the arithmetic that matters is brutally simple: one core fully pegged / four vCPUs on the task = ~25% task-average CPU At full saturation, the busiest that process can ever make the task look is about 25 percent. Add a little async I/O overhead spread across the runtime and you land around 30 percent. That is not a service with headroom. That is a service redlining on the only core it can use, while three cores sit idle and drag the average down to a number that reads as "barely working." The autoscaling policy was tracking average CPU across the task's cores. For a workload that can only ever use one of them, that average is not a measure of load. It is a measure of load divided by four. The metric was answering a different question This is the real lesson, and it is not specific to AWS or ECS. Average CPU utilization answers "how much of th
AI 资讯
Running AI-Generated Code Safely: Field Notes on Vercel Sandbox
Headline: Vercel Sandbox runs untrusted code — including code a model just wrote — inside an isolated, ephemeral microVM instead of inside my application's own process. I moved every "let the model write and execute a snippet" feature off ad-hoc child_process calls and onto Sandbox: one sandbox per execution, a hard timeout, an isolated filesystem, and no path back into my app's environment variables. Key takeaways Vercel Sandbox ( @vercel/sandbox ) runs code inside an isolated Firecracker microVM, not a container in your app's own process — a compromised sandbox can't read your Vercel Function's memory or environment variables. A sandbox is ephemeral: you create one, run commands, read the output, then stop it. There is no persistent state between runs unless you explicitly persist it yourself. sandbox.runCommand() executes a process inside the sandbox and returns stdout, stderr, and an exit code; sandbox.domain(port) exposes a running server on a public URL for a live preview. The two cases I actually reach for it: an LLM-authored script that needs to run and return a result, and a user-facing "run this code" feature like an AI-generated component preview. Sandbox is not the tool for trusted, first-party build or CI logic — that belongs in the deploy pipeline. Sandbox is for code you did not write and do not trust. Why can't I just run AI-generated code inside my own Vercel Function? A Vercel Function shares its process, filesystem, and environment with the rest of my app. Running an untrusted string as code in that same process — through child_process.exec or, worse, eval — puts every secret the function can see, API keys and database URLs included, inside the blast radius of whatever the model wrote. A generated snippet can read environment variables, open an outbound connection to exfiltrate them, or just spin the CPU and starve every other request the function is serving at the same time. I treat any code I did not author myself as untrusted by default, and th
AI 资讯
Building a Bulletproof Comment Reply System in Node.js & MongoDB 🚀
When building a nested reply system, most developers worry about deep tree complexity or messy data structures. For Vlox , I took a different approach: keeping things flat, fast, and secure by reusing a single Mongoose schema with smart atomic limits. Here is a deep dive into how I engineered a production-ready, race-condition-safe reply mechanism using MongoDB transactions, strict type sanitization, and automated limits. How It Works 🛠️ User Action: A user clicks the reply icon and submits their reply. The Payload: Vlox's system sends 3 fields via the endpoint /api/v1/reply/comment/post/:id : id : The post ID (passed as a URL parameter). rootCommentId : The ID of the root comment being replied to. reply : The raw text entered by the user. Sanitization & Validation: The incoming reply is instantly converted to a trimmed string. It then passes through two critical validation checks: Existence Check: The reply must exist. (If a malicious actor sends a payload without a body, the string literally evaluates to "undefined" and gets blocked). Length Limit: The reply must be under 201 characters, enforcing the standard comment limit. Atomic Transactions: If the validation checks pass, the system initiates a Mongoose transaction to execute the following steps safely: Permission Check: It verifies if the user has permission to reply by checking the post's status via await schemas.Posts.findOne(hotQueries.find_user_post(id, req.session.userId)); . Creation: If permissions are valid, it creates a new reply. (Fun fact: It reuses the exact same schema as standard comments!) The Reply Schema Structure: The reply object functions just like a normal comment, with two distinct exceptions: It does not contain a repliesCount field. It includes an extra rootId field, which explicitly points to the ID of the root comment being replied to. Concurrency & Caps: To guarantee that a single comment never receives more than 10 replies while simultaneously incrementing the counter, the system r
AI 资讯
Why Nodemailer Doesn't Work on Cloudflare Workers (And What To Do Instead)
A short explanation of a wall a lot of developers hit, why it isn't going away, and the five lines that replace it. You wrote a contact form. It worked locally. You deployed it to a Cloudflare Worker, or a Vercel Edge Function, or Deno Deploy, and got something like this: TypeError: Class extends value #<Object> is not a constructor or null Or, if you were luckier and got a useful error: Module not found: Can't resolve 'net' Then you spent an hour trying compatibility flags, polyfills, and bundler aliases. I want to save you the rest of that hour. This isn't a bug, and no amount of configuration will fix it. The actual reason Nodemailer's default transport is SMTP. SMTP is a protocol that runs over a raw TCP connection. To open one in Node.js, you call net.createConnection() . Cloudflare Workers don't run on Node.js. They run on V8 isolates — the same engine as Chrome, without the Node runtime around it. Vercel's Edge Runtime and Deno Deploy are built on similar principles. In that environment, there is no net module, because there are no raw TCP sockets. All networking is handled by managed infrastructure outside the runtime — Cloudflare's own writeup on bringing node:http to Workers is explicit about this: connection pooling, TLS negotiation, and egress IP management are handled at the system level, which is precisely why a subset of Node APIs can never be supported. So the chain is: No raw TCP → no net.createConnection() → no SMTP client → no Nodemailer. There's a second, smaller issue that often gets conflated with this one. Nodemailer issue #1621 points out that Nodemailer imports built-in modules without the node: prefix, which breaks the Workers build step. That one is fixable. But fixing it wouldn't help — you'd just move the failure from build time to runtime, where net still doesn't exist. Issue #1623 covers the broader edge-function problem. It's worth being clear that none of this is a knock on Nodemailer. It's an excellent library, actively maintained,
AI 资讯
I stopped letting GPT-5 babysit my inbox and the whole workflow got cheaper and better
I used to think email was a terrible place for AI. Too messy. Too human. Too full of forwarded chains from 2017 and HTML generated by software nobody at the company can name. Then I spent some time reading inbox automation threads, especially a good one on r/openclaw about email flows, and the pattern finally clicked: Email is a great surface for AI if you stop making the model act like your mail server. That sounds obvious. But a lot of inbox automations still do this: new message arrives ask GPT-5 if it is support ask Claude if it is sales ask another model if it is spammy ask again which alias it belongs to ask again whether to reply now or later That is not intelligence. That is expensive amnesia. The better pattern is simple: code owns state, retries, scheduling, sync, and verification the LLM only handles decisions that actually require judgment That split made my inbox workflows cheaper, easier to debug, and way less fragile. The rule I keep coming back to A comment from an OpenClaw workflow discussion said it better than most docs do: If your workflow stops working when you hit your LLM usage limit, the LLM is probably doing too much. That was about coding agents, but it applies perfectly to inbox automation. If your email pipeline depends on a model to remember mailbox state, dedupe events, handle retries, or re-check routing rules every run, you built the wrong system. Models are good at judgment. They are bad at being custodians. Email feels chaotic, but the transport is already structured Humans experience email as chaos. Machines do not. Every message already arrives with useful structure: From To Reply-To Subject thread identifiers message IDs headers timestamps raw MIME attachment boundaries alias addresses That matters because a lot of routing decisions should never hit an LLM in the first place. If invoices always go to ap@company.com , GPT-5 should not be rediscovering that rule every morning. If support mail always lands on a specific alias, code
AI 资讯
Why Your ZATCA Phase 2 Invoice Passes Compliance and Fails Reporting
If you are integrating ZATCA Phase 2 (Saudi Arabia's Fatoora e-invoicing) and you have seen this: { "type" : "ERROR" , "code" : "signed-properties-hashing" , "category" : "CERTIFICATE_ERRORS" , "message" : "Invalid signed properties hashing, SignedProperties with id='xadesSignedProperties'" } ...after your invoice sailed through /compliance/invoices , this post is for you. It is the single most confusing failure mode in the whole integration, and the fix is not what the error suggests. The trap: SignedProperties exists in two byte-shapes The XAdES SignedProperties block is referenced twice in your signed document: ds:Reference URI="#xadesSignedProperties" carries a digest of the block. The block itself is embedded inside ds:Object > xades:QualifyingProperties . The natural assumption is that both refer to the same bytes. They do not. The hashed shape carries namespace declarations and starts at column 0: <xades:SignedProperties xmlns:xades= "http://uri.etsi.org/01903/v1.3.2#" Id= "xadesSignedProperties" > <xades:SignedSignatureProperties> <xades:SigningTime> 2026-08-07T02:14:33 </xades:SigningTime> <xades:SigningCertificate> <xades:Cert> <xades:CertDigest> <ds:DigestMethod xmlns:ds= "http://www.w3.org/2000/09/xmldsig#" Algorithm= "http://www.w3.org/2001/04/xmlenc#sha256" /> The embedded shape carries no namespace declarations (they are inherited from ancestors) and its root element is indented to column 32 : <xades:SignedProperties Id= "xadesSignedProperties" > <xades:SignedSignatureProperties> Embed the hashed shape verbatim - the intuitive thing to do - and the gateway rejects with signed-properties-hashing , even though your indentation "looks right". The second half of the trap: the digest encoding The digest is not the raw SHA-256 bytes in base64. It is base64 of the hex string : const crypto = require ( ' crypto ' ); // hashedShape = the namespaced, column-0 variant above const propsDigest = Buffer . from ( crypto . createHash ( ' sha256 ' ). update ( Buffer .
AI 资讯
Preventing Overselling: Inventory Locks Under Concurrent Checkouts
Two customers are looking at the same product. One unit left. Within the same second, both click Pay. If your checkout reads the stock count, decides there's enough, and then writes the decrement, both requests pass the check and both succeed. You've now sold two units of something you had one of. That's overselling, and it's not a rare edge case — it's the default behaviour of any checkout that treats "check stock" and "reduce stock" as two separate steps. The window is small, but on a product that's nearly sold out, or during a launch when everyone hits the same SKU at once, small windows fire constantly. I've built the order pipeline for two production e-commerce platforms — pikkuna.fi and pi-pi.ee — where concurrent webhooks and concurrent checkouts hit the same order and product rows. This is the layer I reach for when a store sells finite stock. I covered the bare SELECT ... FOR UPDATE primitive briefly in PostgreSQL Production Patterns ; this article is the whole system built on top of it — reservations, multi-line carts, the payment window, and the parts that actually bite you in production. When You Don't Need Any of This Start with the honest disclaimer, because it decides everything downstream. Both pikkuna.fi and pi-pi.ee are made-to-order . A vinyl curtain is cut to the customer's dimensions; a waterless urinal system ships from a supply chain, not a shelf with a hard unit count. When there's no fixed quantity to run out of, overselling isn't a failure mode — you can't sell the tenth unit of something you manufacture on demand. So neither of those platforms needs a row lock on a stock column, and I didn't build one there. You need this article when you sell discrete, finite stock : limited runs, event tickets, one-off items, anything where "5 left" is a real number and selling the sixth is a promise you can't keep. If your catalogue is print-on-demand, made-to-order, or backed by effectively unlimited supply, stop here — the locking below is complexity
AI 资讯
« J'ai fini le tuto Node, et là je suis bloqué » — le mur dont personne ne parle
Tu as fini le tuto. Le vrai, le gros, celui de douze heures. Tu as tout suivi, tout tapé, tout fait tourner. À la fin, l'application marchait. Tu t'es senti capable. Tu t'es dit : « ça y est, je sais faire une API ». Et puis tu as ouvert un dossier vide pour faire la tienne. Curseur qui clignote. index.js . Rien. Pas parce que tu as oublié la syntaxe. Tu la connais. Mais là, tout seul, sans quelqu'un qui te dit quoi taper à la ligne suivante, tu ne sais pas par où commencer. Et cette sensation-là, ce vide entre « j'ai fini le tuto » et « je sais faire », personne ne t'avait prévenu qu'elle existait. C'est de ce mur que je veux parler. Parce que ce n'est pas un défaut chez toi. C'est une étape. 1. Le piège n'est pas le tuto, c'est ce qu'il te cache Un tuto, c'est une suite de bonnes décisions déjà prises pour toi. Quel dossier créer. Quel package installer. Où mettre le fichier de config. Quand extraire une fonction. À chaque embranchement, le formateur a choisi le bon chemin, et toi tu l'as suivi. Tu as tapé du code, oui. Mais tu n'as pris aucune décision. Or coder, le vrai coder, c'est presque que ça : décider. Choisir entre deux structures. Trancher un nom de variable. Décider si ce bout de logique mérite sa propre fonction. Un développeur qui bosse, ce n'est pas quelqu'un qui connaît toutes les réponses — c'est quelqu'un qui sait avancer quand il n'y en a pas. Le tuto t'a entraîné à taper. Il ne t'a pas entraîné à décider. Et c'est exactement la compétence qui te manque devant ton dossier vide. Ce n'est pas un trou dans ton savoir. C'est un muscle que tu n'as jamais sollicité, parce qu'on ne te l'a jamais laissé faire. 2. Pourquoi « un tuto de plus » ne réglera rien Ta réaction instinctive face au blocage, c'est de retourner là où tu te sens compétent. Un autre tuto. Un cours de plus. Une nouvelle techno à cocher. Je comprends le réflexe. Le tuto, c'est confortable : il y a une barre de progression, une fin, une petite dose de « j'ai réussi » à chaque étape. Le d
AI 资讯
Project Explanation for my Chesso application
Project High-Level Summary Chesso is a full-stack, real-time multiplayer chess platform engineered to provide low-latency online gameplay. It features real-time move synchronization, authoritative backend match clocks, secure authentication using JWT and Google OAuth, and full chess rule validation. I built it using the MERN stack (MongoDB, Express, React, Node.js) combined with Socket.IO for bi-directional WebSocket communication and Chess.js for move validation and FEN (Forsyth–Edwards Notation) state management. One of the main challenges I solved was building a server-authoritative state and clock synchronization mechanism to prevent client tampering and handle mid-game reconnections gracefully. Tech Stack & Architectural Overview Frontend : React, Vite for fast builds, React for declarative UI updates upon WebSocket events. Backend API : Node.js, Express.js Event-driven, non-blocking I/O ideal for handling multiple concurrent WebSocket connections. Socket.IO : Provides bi-directional socket events, auto-reconnection fallback, and socket room abstraction. Database : MongoDB for flexible JSON-like document model ideal for storing FEN strings, match logs, and user metadata. Auth & Security : Google OAuth 2.0, Passport.js, JWT, bcryptusing standard authentication flow providing password hashing (bcrypt) and session security via JWT tokens. Implementation of matchmaking & Queueing System When a player clicks "Play", the client emits StartGame with their playerID. The server verifies turn ownership (game.currentP === playerID). The move is executed in an isolated server-side Chess() instance (gameSockets.js). If empty, the player is queued and notified via waitingForOpponent. If another player is waiting, waitingQ.shift() pairs them instantly, creates a new game record in MongoDB (GameModel.js), assigns piece colors (white/black), and joins both sockets into a dedicated Socket.IO room named after the gameID. Game Recovery & Reconnection Resilience The server exposes