">
 

Static Site, Live Inventory: Two Sources of Truth That Don't Fight Each Other

Iniciado por joomlamz, Hoje at 14:30

Respostas: 1   |   Visualizações: 1

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

**Análise Técnica: Plataforma de Inteligência Artificial para Hotel em Go**

Aqui está a minha análise técnica sobre o tóprio "How I Built a Hotel AI Platform in Go (And Every Honest Technical Debt We're Carrying)".

**Introdução**

A plataforma de inteligência artificial para hotel em Go é um projeto ambicioso que visa desenvolver uma solução escalável e confiável para o setor de hospedagem. O artigo apresenta as principais escolhas técnicas e desafios enfrentados pelo desenvolvedor ao longo do processo.

**Arquitetura da Plataforma**

A plataforma é baseada em Go, uma linguagem de programação concorrente e leve, ideal para aplicações de alto tráfego. A arquitetura é composta por vários módulos, incluindo:

* **API de Entrada**: responsável por receber solicitações de entrada e processá-las.
* **Banco de Dados**: usado para armazenar dados de clientes, reservas e outros.
* **Algoritmos de IA**: utilizados para prever tendências e fornecer recomendações personalizadas.
* **Módulo de Notificações**: responsável por enviar notificações a clientes e funcionários.

**Tecnologias Utilizadas**

O desenvolvedor optou por usar as seguintes tecnologias:

* **Go**: linguagem de programação principal.
* **MySQL**: banco de dados de relacionamento.
* **Redis**: banco de dados em memória para armazenar dados de cache.
* **Amazon S3**: armazenamento de dados de imagem e vídeo.

**Desafios Técnicos**

O desenvolvedor enfrentou vários desafios técnicos ao longo do processo, incluindo:

* **Escalabilidade**: garantir que a plataforma possa lidar com um grande volume de solicitações.
* **Concorrência**: lidar com a concorrência de solicitações e garantir a consistência dos dados.
* **Desempenho**: otimizar o desempenho da plataforma para garantir uma experiência de usuário satisfatória.

**Dívida Técnica**

O desenvolvedor reconhece que a plataforma carrega uma dívida técnica significativa, incluindo:

* **Complexidade da Arquitetura**: a arquitetura da plataforma é complexa e difícil de manter.
* **Dependência de Tecnologias**: a plataforma depende de tecnologias específicas que podem mudar ou se tornar obsoletas.
* **Manutenção**: a manutenção da plataforma é uma tarefa constante e exigente.

**Conclusão**

A plataforma de inteligência artificial para hotel em Go é um exemplo de como uma solução escalável e confiável pode ser desenvolvida usando Go e outras tecnologias. No entanto, a dívida técnica que a plataforma carrega é significativa e requer uma atenção constante para garantir a sua manutenção e evolução.

**Alojamento de Alta Performance para Vossos Projetos**

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com. Nossa infraestrutura de armazenamento e processamento é projetada para lidar com um grande volume de solicitações e garantir a consistência dos dados. Além disso, nossa equipe de suporte é sempre pronta para ajudar a resolver qualquer problema que você possa ter.

Static Site, Live Inventory: Two Sources of Truth That Don't Fight Each Other



Tópico: Static Site, Live Inventory: Two Sources of Truth That Don't Fight Each Other
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
The shop sells two things: original watercolour paintings (one of each, ever) and open-edition prints. Originals sell out permanently. Prints don't. The question the architecture has to answer is: how does the site know which originals are still available, and how quickly does it reflect a sale?

The naive answer is to fetch from Medusa at build time and bake the sold status into the static HTML. That works until a painting sells between deploys — the site shows it as available, someone clicks "Add to cart," Medusa rejects the request, and the experience is broken. Rebuilding on every sale is an option, but it couples the storefront's uptime to Medusa's webhook reliability.

The naive answer in the other direction is to fetch from Medusa client-side on every page load and render nothing until the data arrives. That's a spinner on a content site. The paintings are the product. Making visitors wait to see them is the wrong trade.

The actual solution has two layers with clearly defined responsibilities.



Layer 1: build-time hint


Every painting in the content collection has an optional sold field in its frontmatter:

---
title: "Autumn Morning"
sold: true
---

When sold: true, the build-time effects are:


Catalog feed: the original variant is excluded from the Google/Meta product catalog TSV. No point advertising something that can't be bought.


JSON-LD: the product structured data uses OutOfStock for availability. Google doesn't index it as a purchasable product.


OG tags: product:availability is set to "oos".

None of these affect the shop UI. A sold-out painting still has a page, still shows in the gallery, still shows the print options. The sold flag is a build-time signal to external systems, not a UI gate.

The flag is kept in sync automatically. bun run sync reads stocked_quantity from Medusa for every product and patches the frontmatter:

↕ autumn-morning → sold: true
↕ winter-estuary → removed sold flag (back in stock)

↕ in the output means a patch was written. Running sync before deploying keeps the catalog and structured data accurate without manual frontmatter edits.



Layer 2: runtime hydration


The shop grid is static Astro HTML. Every card renders with data-status="available" by default — the optimistic assumption. The original price, the "Add to cart" button, the availability badge: all rendered at build time, all assuming the painting is available.

After the page loads, a plain <script> block calls the Medusa store API and patches each card:

async function hydrateAvailability() {
const products = await fetchProducts() // cached promise, fires once per page

cards.forEach((card) => {
const handle = card.dataset.handle
const availability = products.get(handle)
const originalAvailable = availability?.originalAvailable ?? true // optimistic fallback

card.dataset.status = originalAvailable ? 'available' : 'sold'

if (!originalAvailable) {
card.querySelector('.variant-original')?.setAttribute('data-sold', '')
}
})
}

hydrateAvailability()

data-sold on the original variant row triggers CSS: the price gets a strikethrough, the row fades slightly, the "Add to cart" button disappears. The card stays in the grid — sold originals are visible as FOMO and context, not hidden. Prints on the same painting remain fully purchasable.

No framework. No Svelte island. No loading state. The grid is visible and interactive immediately; the sold indicators arrive silently a few hundred milliseconds later without shifting anything.



What happens when Medusa is down


The optimistic fallback on line 6 above is intentional. If fetchProducts() fails — Medusa is restarting, the VPS is briefly unreachable — every card stays data-status="available". Visitors can browse. The cart still works. If someone tries to add a sold original, Medusa rejects the cart request and the UI shows the error then.

The worst case is a few extra "sorry, sold out" cart errors during a brief backend outage. The alternative — blocking the grid on a Medusa response — would mean a broken shop during any downtime. For a low-traffic art shop, optimistic-with-graceful-degradation is the right default.



The filter system


The shop grid has filters: show all / available originals only / prints only / by theme. The filters use data-hidden (not display:none) driven by data-status and data-tags:

function applyFilters() {
cards.forEach((card) => {
const hidden = shouldHide(card, activeFilter, activeTags)
card.dataset.hidden = String(hidden)
})
}

CSS transitions on data-hidden give the appearance/disappearance a fade rather than a jump. The "available originals" filter count updates after hydrateAvailability() completes — it reads the live data-status values, not the build-time assumptions.



Why two layers instead of one


Build-time data is fast and free — it's just frontmatter. Runtime data is live and accurate. The split is about matching the right data source to the right consumer:

• External systems (Google, Meta) see the build-time state. They cache it. A slightly-stale catalog entry means a sold original might briefly appear in Google Shopping — a bad click, but not a broken purchase (Medusa rejects the cart). Running bun run sync before each deploy keeps the gap small.

• The shop UI sees the runtime state. A "available" badge on an actually-sold painting is a much worse experience — someone browses, adds to cart, gets rejected. That one must be live.

bun run sync closes the gap before each deploy, so the build-time state is never more than one deploy behind. In practice, originals sell slowly enough that the gap is rarely more than a few hours.

If you're applying this on a different stack, the principle generalises: optimistic static HTML + silent runtime patch + accept that the worst case is a cart error. The trick is being honest about which data source serves which consumer, and not making the visitor wait for the slow one.



When this pattern doesn't fit


Optimistic-with-graceful-degradation is the right default for a low-traffic shop where originals sell on the order of days. It's the wrong default for a flash sale, a sneaker drop, or anything where stock depletes in seconds and a misleading "available" badge would mean hundreds of cart errors a minute. At that point the spinner stops being a UX failure and starts being an honest signal — "we're checking, because the answer changes faster than we can ship HTML."

That's the full series. The stack behind nadiapoe.co.uk: Astro 6 + Svelte on Cloudflare Pages, Medusa v2 on a €3.29/mo Hetzner VPS, and a handful of patterns that took longer to figure out than they should have.


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: