AI 资讯
Manticore Speaks MySQL - So I Made It a Laravel Database Driver Instead of a Scout Engine
The problem I've been working with Manticore Search for about two years at EricaPRO , building the search layer for two financial data platforms. For the past year, that work has been a Laravel API. Manticore was never the problem. It's fast and it's stable. The problem was the gap between Manticore and Laravel. I had already built a package for this — laravel-manticore-search , a fluent builder over Manticore's HTTP/JSON API. It works, and it's still in use. But it's a client wrapper. Every feature had to be implemented manually. Every new filter or facet meant more custom architecture around the client, and none of the things Laravel gives you for free — models, migrations, pagination, casts — applied to it. Scout doesn't close that gap either. Scout gives you search() . No full query builder, no migrations for your indexes, sync is your problem. That's not a criticism — Scout abstracts over engines with completely different APIs, so it exposes the lowest common denominator. It just wasn't what I needed. What I needed was simple to describe and annoying to not have: something plug and play. Something Laravel way. Point Eloquent at Manticore and use Eloquent. The insight Manticore speaks the MySQL wire protocol. Out of the box, port 9306. You can connect to it with any MySQL client and run SQL. I had been using that port for two years without thinking about what it meant for Laravel. Because here's the thing: all of Eloquent — models, query builder, migrations, pagination, chunking — sits on top of a Connection and a Grammar . The grammar compiles builder calls into SQL for a specific dialect. That's the entire mechanism behind Laravel supporting MySQL, Postgres, SQLite and SQL Server with one codebase. So the real question was never "how do I re-implement Eloquent on top of Manticore's client?" It was "how thin can a Manticore grammar be?" If Manticore accepts MySQL-protocol connections and mostly-MySQL SQL, then a Laravel database driver — a custom connection plu
AI 资讯
LLM Evaluation System Prompts Scored Rubrics Runtime Guardrails: A Practical Guide for Production
LLM Evaluation System Prompts Scored Rubrics Runtime Guardrails: A Practical Guide for Production Learn how to evaluate LLM outputs in production using system prompts, scored rubrics, and runtime guardrails to prevent hallucinations and ensure quality. TL;DR: To evaluate LLM outputs in production, combine system prompts that define evaluation criteria, scored rubrics using LLM-as-a-judge for dimensions like correctness and relevance, and runtime guardrails that filter or flag unsafe outputs. This approach scales better than human review, adapts via prompt changes, and catches failures that status codes miss, as seen in the Air Canada chatbot case. Why Production LLM Evaluation Demands More Than Status Codes A 200 status code only confirms the server processed the request—it says nothing about whether the generated text is factual, safe, or useful. The Air Canada chatbot that invented a non-existent bereavement discount returned perfectly valid HTTP responses, yet the hallucinated policy led to a tribunal ruling against the airline. Production evaluation must therefore separate operational health (latency, error rates) from output quality (correctness, relevance, harmlessness). Consider a typical API call that succeeds operationally but fails qualitatively: import requests response = requests . post ( " https://api.example.com/v1/chat " , json = { " model " : " gpt-4o " , " messages " : [{ " role " : " user " , " content " : " What is Air Canada ' s bereavement policy? " }]}, headers = { " Authorization " : " Bearer $KEY " } ) print ( response . status_code ) # 200 print ( response . json ()[ " choices " ][ 0 ][ " message " ][ " content " ]) # Output: "Air Canada offers full refunds for bereavement-related cancellations..." A 200 status code and a well-formed JSON body mask a completely fabricated policy. To catch this, you need a separate evaluation layer that scores the output against a rubric. LLM-as-a-judge is a common approach, using a second model to assess the
AI 资讯
HTTP Server — Request Lifecycle
Request lifecycle: một HTTP request đi qua đâu, và vì sao "quên gọi next()" làm request treo cho tới khi socket timeout Một request tới một Express hay Fastify server không phải là "gọi handler rồi trả về response". Nó là một chuỗi các bước theo thứ tự cố định: parse HTTP, chạy qua middleware/hook, match route, gọi handler, serialize, gửi response, đóng. Nếu bất kỳ bước nào không chuyển tiếp — Express không gọi next() , Fastify hook không reply.send() hay không return — request treo cho tới khi client hoặc server timeout đóng socket. Đây là loại lỗi không ném exception, không xuất hiện trong error log, chỉ hiện ra qua p99 latency phình lên và số socket ở trạng thái ESTABLISHED tăng dần. Hiểu chính xác lifecycle này là điều kiện tiên quyết để debug những request "biến mất" và để đặt middleware đúng thứ tự. Cơ chế hoạt động Bước dưới cùng giống nhau ở cả hai framework: Node core http.Server nhận TCP connection, parse HTTP request line + headers, phát event request với hai object IncomingMessage (req) và ServerResponse (res). Điểm khác nhau là những gì framework làm giữa lúc nhận request và lúc response ra khỏi socket. Express dựng một chuỗi middleware qua Router . Mỗi lần app.use(fn) hay app.get(path, fn) được gọi, Express bọc fn vào một Layer với path regex (thông qua path-to-regexp ) rồi push vào một stack. Khi request đến, Router.handle duyệt stack tuần tự: với mỗi layer, nếu path match, gọi fn(req, res, next) . next() là closure trỏ vào layer kế tiếp; chỉ khi nó được gọi thì layer sau mới chạy. Error handler được nhận diện bằng arity — hàm 4 tham số (err, req, res, next) — và chỉ được duyệt tới khi next(err) được gọi: import express from ' express ' const app = express () app . use ( express . json ({ limit : ' 1mb ' })) // 1. parse body app . use (( req , _res , next ) => { // 2. request id req . id = crypto . randomUUID () next () }) app . use (( req , _res , next ) => { // 3. auth const token = req . headers . authorization if ( ! token ) return next ( new Erro
AI 资讯
Chrome for Developers a Berlino: cosa aspettarsi dall’ecosistema web nel 2026
Tra performance, piattaforma e toolchain: i temi che contano davvero per chi costruisce frontend oggi. Il frontend nel 2026 è diventato una disciplina sempre più “di prodotto”: non basta far funzionare l’interfaccia, serve che sia veloce, stabile, accessibile e misurabile in produzione. E quando l’ecosistema Chrome parla di “connessione” tra developer e piattaforma, il messaggio utile per chi lavora sul web è semplice: capire dove investire tempo per ottenere impatto reale sugli utenti . Di seguito, una lettura pratica dei temi che continuano a emergere come prioritari per chi costruisce applicazioni e siti moderni. 1) Performance: meno benchmark, più realtà La performance non è più un esercizio di ottimizzazione a fine progetto. È un requisito continuo che va gestito con strumenti, metriche e processi. Cosa significa “misurabile” oggi Metriche di campo (real user monitoring) : le prestazioni che contano sono quelle che arrivano dai dispositivi reali, su reti reali. Metriche di laboratorio : restano utili per regressioni e CI, ma vanno interpretate come “segnali” e non come verità assolute. Implicazione pratica Imposta una pipeline dove: le metriche sintetiche bloccano regressioni evidenti (build/PR), le metriche reali guidano le priorità (release e backlog). 2) DevTools: dal debug al controllo qualità Gli strumenti di sviluppo non servono più solo a “trovare il bug”, ma a ridurre il rischio : regressioni di layout, memory leak, risorse inutili, dipendenze pesanti. Abitudini che fanno differenza Profilare prima di ottimizzare: CPU, rete e rendering hanno colli di bottiglia diversi. Isolare i cambiamenti: una variazione di bundling o di immagini può ribaltare il profilo prestazionale più di una micro-ottimizzazione in JS. 3) La piattaforma web continua a crescere (e chiede scelte più consapevoli) La Web Platform oggi offre API potenti, ma la parte difficile non è “usarle”: è scegliere quando usarle. Un criterio utile Se una feature riduce complessità (meno librerie,
AI 资讯
Ensuring Thread Safety — .NET core-centric
Prefer immutability What: Make data read-only after construction. Instead of editing objects, create new ones. Why: If nothing changes, many threads can read safely with no locks . How (.NET): public readonly record struct Money ( decimal Amount , string Currency ); public record Order ( Guid Id , IReadOnlyList < OrderLine > Lines ) { public Order AddLine ( OrderLine line ) => this with { Lines = Lines . Append ( line ). ToList () }; } Use record / readonly struct , IReadOnlyList<> , and with (copy-on-write). Keep collections immutable ( ImmutableList<T> , ImmutableDictionary<K,V> ). Avoid shared state What: Don’t let unrelated code touch the same mutable object. Why: If each operation owns its data, there’s nothing to synchronize. How: Per-request scope : create new service instances that hold request-specific state. No static mutable fields; if you must cache, use ConcurrentDictionary : private static readonly ConcurrentDictionary < string , Widget > _cache = new (); var widget = _cache . GetOrAdd ( key , k => LoadWidget ( k )); Use lock / SemaphoreSlim cautiously What: Synchronization primitives that serialize access to critical sections. When: Short, minimal critical sections where mutation is unavoidable. lock for synchronous code; SemaphoreSlim when await is involved (never block in async code). Patterns & pitfalls: private readonly object _gate = new (); void Update () { lock ( _gate ) // keep work tiny inside { // mutate a small piece of shared state _count ++; } } private readonly SemaphoreSlim _sem = new ( 1 , 1 ); async Task UpdateAsync () { await _sem . WaitAsync (); try { _count ++; } finally { _sem . Release (); } } Never lock(this) or a public object (external code could deadlock you). Keep lock duration short; avoid I/O under locks. If multiple locks are needed, fix a global order to prevent deadlocks. Atomic counters (avoid locks entirely): Interlocked . Increment ( ref _count ); Leverage actor-style or message queues What: Push work as messages to
AI 资讯
Synchronous vs asynchronous in .NET core - how decide
Rule of thumb If your action waits on something external , make it async . If it’s instant CPU , keep it sync ; for expensive CPU , offload . The core idea Async shines for I/O-bound work (DB calls, HTTP calls, queues, files). It frees the request thread while waiting, so the server can serve more requests with the same thread pool . Sync is fine for trivial, short CPU work (formatting, small calculations) where you’re not awaiting anything and the handler returns in a few milliseconds. When to choose async You call EF Core ( SaveChangesAsync , ToListAsync ), HttpClient , Azure SDK ( ServiceBusClient , BlobClient ), file I/O, or any API with Async methods. You expect latency from a dependency (tens–hundreds of ms). You need cancellation and timeouts (propagate HttpContext.RequestAborted ). When sync is acceptable The action is pure CPU and trivial (e.g., quick math, mapping, input validation) and returns immediately. There are no I/O waits and no benefit from freeing the thread. If it’s CPU-heavy (image processing, big JSON transforms), do not just make it async—offload to a background queue/worker or a separate compute service. Async won’t make CPU faster. Pitfalls to avoid Don’t block async : never use .Result / .Wait() on Tasks (deadlocks/thread-pool starvation). Async all the way down : if the controller is async, downstream calls should be too. Don’t fake async : returning Task.Run around synchronous I/O just burns threads. Keep concurrency bounded when fanning out to multiple I/O calls. Mini decision checklist Any I/O? → Use async (end-to-end). Pure CPU? Tiny (≤ a few ms) → Sync is fine. Heavy/variable → Offload to background worker; controller returns 202/Location or uses a queue. ASP.NET Core examples Async (I/O-bound) — recommended [ ApiController ] [ Route ( "orders" )] public class OrdersController : ControllerBase { private readonly OrdersDbContext _db ; private readonly HttpClient _http ; public OrdersController ( OrdersDbContext db , IHttpClientFactory
开发者
Service Discovery in Modern .NET Applications and Azure
This article is part of the Comprehensive Guide to Microservices Architecture in .NET Core, Cloud and Azure series. Service Discovery in Kubernetes How Kubernetes DNS Works Kubernetes automatically creates DNS entries for services, enabling simple name-based discovery. A service named order-service in the production namespace becomes accessible at order-service.production.svc.cluster.local . For services within the same namespace, you can use the short name order-service . Service Definition: apiVersion : v1 kind : Service metadata : name : order-service namespace : production labels : app : order-service version : v1 spec : selector : app : order-service ports : - name : http protocol : TCP port : 80 targetPort : 8080 type : ClusterIP Native Service Discovery in .NET 9 .NET 9 introduces enhanced service discovery capabilities with improved configuration and resilience features. Basic Configuration: // Program.cs var builder = WebApplication . CreateBuilder ( args ); // Add service discovery with .NET 9 enhancements builder . Services . AddServiceDiscovery (); // Configure HTTP client with service discovery builder . Services . AddHttpClient < IOrderServiceClient , OrderServiceClient >( client => { // Use service name - discovery resolves to actual endpoint client . BaseAddress = new Uri ( "http://order-service" ); }) . AddServiceDiscovery () . AddStandardResilienceHandler (); // .NET 9 resilience patterns var app = builder . Build (); Advanced Configuration with appsettings.json: { "ServiceDiscovery" : { "Providers" : { "Kubernetes" : { "Namespace" : "production" , "RefreshPeriod" : "00:01:00" } }, "Services" : { "order-service" : { "Scheme" : "https" , "EndpointNames" : [ "http" , "https" ], "HealthCheckPath" : "/health" }, "payment-service" : { "Scheme" : "http" , "AllowAllHosts" : false } }, "AllowAllHosts" : true , "AllowedHosts" : [ "*.svc.cluster.local" ] } } Service-to-Service Communication Patterns Using Typed HTTP Clients: public interface IOrderServiceCli
产品设计
.NET 11 Preview 5: Brings File-Based App Improvements, New C# Features, and a Blazor Validation Wave
Microsoft has released the fifth preview of .NET 11, with updates across the SDK, C#, ASP.NET Core, .NET MAUI, and EF Core. Highlights include file-based app improvements, new C# closed classes and unions, a Blazor validation wave, a large MAUI reliability rollup, and SQL Server 2022 as the default EF Core compatibility level. By Almir Vuk
AI 资讯
Kiro as AI Partner for MS SQL Server Optimization on .NET Core: Yang Biasa Berhari-hari, Sekarang Hitungan Jam
Dulu, nyari query yang bikin database spike itu bisa makan berhari-hari. Yang nyari capek, yang nge-fix juga capek. Sekarang? Hitungan jam — dan bonusnya, sambil belajar hal baru juga. Ceritanya begini. Kalau kamu pernah kerja di aplikasi yang pakai ORM (Object-Relational Mapping — semacam "penerjemah otomatis" antara code dan database), pasti familiar sama situasi ini: database tiba-tiba lambat, kamu dapet raw query yang jadi biang kerok, tapi di codebase kamu nulis pakai syntax ORM yang bentuknya beda jauh dari SQL mentah itu. Buat yang belum pernah deal sama ORM, bayangin gini: kamu nulis pesan dalam bahasa Indonesia, lalu ada "penerjemah otomatis" yang convert jadi bahasa Jepang sebelum dikirim ke penerima. Suatu hari ada masalah di pesan yang terkirim — tapi kamu cuma bisa lihat versi bahasa Jepang-nya. Nyari bagian mana dari tulisan Indonesia kamu yang bikin terjemahan-nya bermasalah? Itu effort-nya yang bikin pengen balik tidur aja. Sekarang dengan bantuan Kiro, cukup kasih raw query + akses ke codebase, dia otomatis nyari bagian mana di code yang nge-generate query bermasalah itu. Yang dulu butuh berhari-hari, sekarang bisa selesai dalam hitungan jam — dan itu baru tahap investigasi, belum termasuk fixing-nya. Ceritanya Kenapa Bisa Pakai Kiro Akhir-akhir ini lagi aktif pakai Kiro di tempat kerja. Awal tahun lalu kantor dapat credits melalui program Kiro for Startup , jadi ya sekalian dimaksimalkan. Selain buat debug dan explore query di MS SQL Server, kadang pakai Kiro juga buat analisa log AWS CloudWatch — sambil kasih context aplikasi yang running biar analisa-nya lebih akurat dan gak generic. Di tulisan kali ini, saya mau sharing gimana pakai Kiro sebagai partner beberapa minggu terakhir buat improve query performance di aplikasi .NET Core. Kenapa "partner"? Karena Kiro-nya gak boleh langsung akses ke database — jadi wajib melalui perantara saya. Kita discuss, kolaborasi, dan nge-solve bareng. Bukan AI yang dikasih tombol terus disuruh jalan sendiri. Wakt
AI 资讯
Blazor SSR Gets Client-Side Validation in .NET 11 Preview 5 — No More Round-Trips Just to Show a Red Border
Blazor SSR Gets Client-Side Validation in .NET 11 Preview 5 If you've built Blazor Server-Side Rendering (SSR) forms, you know the pain: a user fills out a form, hits submit, the form posts to the server, the server runs validation, and only then does the user see the "This field is required" message next to the empty email field. That round-trip latency adds up. It breaks the immediacy users expect from modern web apps. .NET 11 Preview 5 fixes this. Blazor SSR forms now get instant, in-browser validation feedback — no server required. The server renders your validation rules as metadata, and Blazor's JavaScript enforces them client-side. Same DataAnnotationsValidator component you already use. Zero code changes needed. Let's break down how it works. Before .NET 11: The SSR Validation Gap In .NET 8 and 9, Blazor SSR rendered HTML on the server and sent it down. Validation only ran server-side — on form submission. If a field was invalid, the whole form posted to the server, came back with validation messages, and re-rendered. Interactive Blazor modes (Server, WebAssembly, Auto) had instant client-side validation because an active SignalR circuit or WASM runtime ran the validation logic locally. But SSR mode — the simplest, most performant option — was left out. The result? Developers who chose SSR Blazor for its simplicity had to choose between: Accepting the laggy validation UX Adding a second JavaScript validation library (and maintaining two validation rulesets) Re-architecting to use an interactive render mode None of these are great options. What Changed in .NET 11 Preview 5 The .NET team shipped two PRs ( #66441 and #66420 ) that bring unobtrusive client-side validation to Blazor SSR forms. The key insight: The .NET model stays the single source of truth. On form render, the server serializes your DataAnnotations validation rules into HTML metadata attributes. Blazor's JavaScript reads those attributes and applies them client-side — the same approach ASP.NET M
AI 资讯
F# vs C# 3 — Conclusions
What can I say. Anyone claiming that F# is good mostly for finance and data processing and C# for everything else, has probably never written a single line of practical F# code. In previous two parts of the article, I tried to demonstrate that with F# you can achieve the same goals as with C#, but with less verbose, repetitive, structural code. How it started. At some point, developers realized that global state with unrestricted data access causes many side effects, producing insecure, error-prone, and hard-to-maintain code as software grows larger. That is when the idea emerged to bring data and the code operating on it together into a single unit, restricting direct access to the unit’s internal state and making software more secure and predictable. This is how data encapsulation was born. Alongside encapsulation, abstraction was introduced — the process of hiding how behavior works. Encapsulation ( hiding data ) and abstraction ( hiding behavior ) remain two foundational pillars of Object-Oriented Programming. And that is how OOP has worked ever since — developers bring data and behavior together ( classes ) and define abstractions for them ( interfaces ). For example, for C# developers — including myself — this has become a daily routine. And we rarely question it, because OOP languages like C# leave us little choice but to structure code this way. But if you ask yourself whether this repetitive routine is always necessary, the answer is — no. You don’t need OOP concepts to build stateless, streamlined request–response, data-processing pipelines, because in such systems there is no long-lived state to hide and protect. You have a request, and almost immediately you have a response. After that, everything is gone. That is what I tried to demonstrate in the first two parts of this article by applying FP concepts. And even if you have a classical desktop application, you don’t always need to approach it in an OOP way. Functional programming handles side effects no