diff --git a/src/content/docs/en/pages/guides/kv-store/manage-data.mdx b/src/content/docs/en/pages/guides/kv-store/manage-data.mdx new file mode 100644 index 0000000000..916ea16d2e --- /dev/null +++ b/src/content/docs/en/pages/guides/kv-store/manage-data.mdx @@ -0,0 +1,84 @@ +--- +title: How to manage KV Store with Edge Functions +description: >- + +meta_tags: 'edge sql, storage, cloud, SQL, sqlite, data' +namespace: documentation_products_kv_store_manage_edge_functions +permalink: /documentation/products/guides/kv-store/manage-with-functions/ +--- + +import LinkButton from 'azion-webkit/linkbutton' + +See how to retrieve data from a with KV Store and Edge Functions. + + + +--- + +## Requirements + +- [Azion Edge Functions enabled](/en/documentation/products/build/edge-application/edge-functions/). +--- + +## Creating a kv +: +--- + +## Creating an edge function to communicate with KV Store + +1. Access [Azion Console](https://console.azion.com). +2. On the upper-left corner, select **Edge Functions** in the **Edge Libraries** section. +3. Click the **+ Edge Function** button. +4. Choose a name for your function. +5. Delete the placeholder function that is inside the code editor. +6. Paste the following code: + +```js +import { Database } from "azion:sql"; + +async function db_query() { + let connection = await Database.open("mydatabase"); + let rows = await connection.query("select * from users"); + let column_count = rows.columnCount(); + let column_names = []; + for (let i = 0; i < column_count; i++) { + column_names.push(rows.columnName(i)); + } + let response_lines = []; + response_lines.push(column_names.join("|")); + let row = await rows.next(); + while (row) { + let row_items = []; + for (let i = 0; i < column_count; i++) { + row_items.push(row.getString(i)); + } + response_lines.push(row_items.join("|")); + row = await rows.next(); + } + const response_text = response_lines.join("\n"); + return response_text; +} + +async function handle_request(request) { + if (request.method != "GET") { + return new Response("Method not allowed", { status: 405 }); + } + try { + return new Response(await db_query()); + } catch (e) { + console.log(e.message, e.stack); + return new Response(e.message, { status: 500 }); + } +} + +addEventListener("fetch", (event) => + event.respondWith(handle_request(event.request)) +); +``` + + + + + + + diff --git a/src/content/docs/en/pages/main-menu/reference/store/kv-store/kv-store.mdx b/src/content/docs/en/pages/main-menu/reference/store/kv-store/kv-store.mdx new file mode 100644 index 0000000000..5e445d78f8 --- /dev/null +++ b/src/content/docs/en/pages/main-menu/reference/store/kv-store/kv-store.mdx @@ -0,0 +1,127 @@ +--- +title: KV Store +description: >- + +meta_tags: 'kv, storage, key, distributed, queries' +namespace: docs_edge_sql +permalink: /documentation/products/store/kv-store/ +--- + +import Tag from 'primevue/tag' +import LinkButton from 'azion-webkit/linkbutton' + + + Preview + + + +## Overview + +KV Store is a distributed key–value storage service that runs across Azion’s edge network. It lets you persist and retrieve small pieces of data with very low latency from anywhere your users are, without managing servers. + +Typical use cases include: + +- Session and authentication tokens +- User preferences and personalization +- Caching API responses and computed fragments +- Rate-limit counters and idempotency keys +- Shopping cart or draft state + +--- + +## How it works + +- Data is organized into namespaces that contain independent sets of keys. +- Each item is addressed by a key that is unique within its namespace. +- Values can be stored as text, JSON, or binary/streaming payloads. +- Data is replicated across Azion edge nodes to maximize availability and read performance. +- Single-key operations are atomic per key. Multi-key transactions are not supported. + +--- + +## Implementation resources + + +| Scope | Resource | +| ----- | -------- | +| Manage KV store with Edge Functions | [How to manage KV store with Edge Functions](/en/documentation/products/guides/kv-store/manage-with-functions/) | +| xxx [How to xxxxx](xxxxxx/) | +--- + +## Business rules + + + +--- + +## Data resilience + +KV Store uses a distributed architecture with replication across Azion edge nodes. New writes are accepted at the edge and propagated to replicas to ensure durability and high availability. Reads are served from the closest healthy replica to minimize latency. + +--- + +## Namespaces + +A namespace is an isolated key space. Use namespaces to segment data by application, environment, or workload. + +Recommended patterns: + +- Separate namespaces for production and staging. +- Prefix keys to model hierarchy, for example: users/123/profile, flags/new-ui, carts/region-br/user-42. +- Keep keys short and meaningful; prefer a few path-like segments over long opaque identifiers. + +Naming: + +- Names must be unique within your account. +- Use lowercase letters, numbers, dashes, and underscores. + +--- + + +## Interacting with KV Store via Edge Functions + +(Create, Read, Update, Delete) +The examples below illustrate common patterns. + + +```js +const aqui=1 +``` + +--- + +## Methods + +- put(namespace, key, value, options?) + - value: string | object (JSON) | ArrayBuffer | ReadableStream + - options: { metadata?: object, contentType?: string } + - returns: void +- get(namespace, key, options?) + - options: { type: 'text' | 'json' | 'arrayBuffer' | 'stream' } + - returns: string | object | ArrayBuffer | ReadableStream +- delete(namespace, key) + - returns: void + + +--- + +## Limits + +These are the **default limits**: + +- Per-key write rate: up to 1 write per second to the same key. +- Key size: up to 512 bytes (UTF‑8). +- Metadata size: up to 1024 bytes (JSON-serialized). +- Value size: up to 25 MB per item. + + +These are the **default limits** for each Service Plan: + +| Scope | Developer | Business | Enterprise | Mission Critical | +| ----- | --------- | -------- | ---------- | ---------------- | +| Namespaces | 10 | 50 | 200 | 200 | +| Maximum file size | 200 MB | 500 MB | 2 GB | 2 GB | +| Maximum storage per account | 5 GB | 50 GB | 300 GB | 300 GB | + + +--- diff --git a/src/content/docs/pt-br/pages/menu-principal/referencia/store/kv-store/kv-store.mdx b/src/content/docs/pt-br/pages/menu-principal/referencia/store/kv-store/kv-store.mdx new file mode 100644 index 0000000000..c62f970ccd --- /dev/null +++ b/src/content/docs/pt-br/pages/menu-principal/referencia/store/kv-store/kv-store.mdx @@ -0,0 +1,121 @@ +--- +title: KV Store +description: >- + +meta_tags: 'kv, armazenamento, chave, distribuído, consultas' +namespace: docs_edge_sql +permalink: /documentacao/produtos/store/kv-store/ +--- + +import Tag from 'primevue/tag' +import LinkButton from 'azion-webkit/linkbutton' + + + Previsualização + + + +## Visão Geral + +KV Store é um serviço de armazenamento de chave-valor distribuído que opera em toda a rede de borda da Azion. Ele permite que você persista e recupere pequenos pedaços de dados com muito baixa latência de qualquer lugar onde seus usuários estejam, sem precisar gerenciar servidores. + +Casos de uso típicos incluem: + +- Sessões e tokens de autenticação +- Sinalizadores de recurso e agrupamentos de A/B testing +- Preferências de usuário e personalização +- Cache de respostas de API e fragmentos computados +- Contadores de limite de taxa e chaves de idempotência +- Estado do carrinho de compras ou rascunho + +--- + +## Como funciona + +- Os dados são organizados em namespaces que contêm conjuntos independentes de chaves. +- Cada item é endereçado por uma chave que é única dentro de seu namespace. +- Os valores podem ser armazenados como texto, JSON ou cargas úteis binárias/em fluxo. +- Os dados são replicados entre pronomes de borda da Azion para maximizar a disponibilidade e o desempenho de leitura. +- Operações de chave única são atômicas por chave. Transações de múltiplas chaves não são suportadas. + +--- + +## Recursos de Implementação + +| Âmbito | Recurso | +| ----- | -------- | +| Gerenciar KV store com Edge Functions | [Como gerenciar KV store com Edge Functions](/pt-br/documentacao/produtos/guias/kv-store/gerenciar-com-funcoes/) | +| xxx [Como xxxxx](xxxxxx/) | +--- + +## Regras de Negócio + +## Resiliência de Dados + +KV Store usa uma arquitetura distribuída com replicação entre pronomes de borda da Azion. Novas gravações são aceitas na borda e propagadas para réplicas para garantir durabilidade e alta disponibilidade. Leituras são servidas da réplica saudável mais próxima para minimizar a latência. + + +--- + +## Namespaces + +Um namespace é um espaço de chave isolado. Use namespaces para segmentar dados por aplicação, ambiente ou carga de trabalho. + +Padrões recomendados: + +- Namespaces separados para produção e staging. +- Prefixe chaves para modelar hierarquia, por exemplo: users/123/profile, flags/new-ui, carts/region-br/user-42. +- Mantenha as chaves curtas e significativas; prefira alguns segmentos do tipo caminho em vez de longos identificadores opacos. + +Nomenclatura: + +- Os nomes devem ser únicos dentro da sua conta. +- Use letras minúsculas, números, hifens e sublinhados. + +--- + +## Interação com KV Store via Edge Functions + +Os exemplos abaixo ilustram padrões comuns. + +```js +const aqui=1 +``` + +--- + +## Métodos + +- put(namespace, key, value, options?) + - value: string | object (JSON) | ArrayBuffer | ReadableStream + - options: { metadata?: object, contentType?: string } + - returns: void +- get(namespace, key, options?) + - options: { type: 'text' | 'json' | 'arrayBuffer' | 'stream' } + - returns: string | object | ArrayBuffer | ReadableStream +- delete(namespace, key) + - returns: void + + + +--- + +## Limites + +Estes são os **limites padrão**: + +- Taxa de gravação por chave: até 1 gravação por segundo para a mesma chave. +- Tamanho da chave: até 512 bytes (UTF-8). +- Tamanho dos metadados: até 1024 bytes (JSON-serializado). +- Tamanho do valor: até 25 MB por item. + + +Estes são os **limites padrão** para cada Plano de Serviço: + +| Âmbito | Desenvolvedor | Negócios | Empresarial | Missão Crítica | +| ----- | --------- | -------- | ---------- | ---------------- | +| Namespaces | 10 | 50 | 200 | 200 | +| Tamanho máximo do arquivo | 200 MB | 500 MB | 2 GB | 2 GB | +| Armazenamento máximo por conta | 5 GB | 50 GB | 300 GB | 300 GB | + +---