diff --git a/apps/docs/src/content/docs/en/pages/build/application-accelerator/how-it-works.mdx b/apps/docs/src/content/docs/en/pages/build/application-accelerator/how-it-works.mdx index 1f3bbbfd75..cd4069f4ab 100644 --- a/apps/docs/src/content/docs/en/pages/build/application-accelerator/how-it-works.mdx +++ b/apps/docs/src/content/docs/en/pages/build/application-accelerator/how-it-works.mdx @@ -9,9 +9,11 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -When the response to one URL depends on a cookie, a device, or a request body, the cache has to tell those requests apart. In an [Application](/en/documentation/platform/applications/), adding those inputs to the cache key requires [Application Accelerator](/en/documentation/platform/applications/application-accelerator/), a Platform Resource that unlocks four capabilities for the cache and the rules. Application Accelerator is off in a new Application, and each Application turns it on separately, in the Application's `modules.application_accelerator.enabled` field in the API. Each [cache setting](/en/documentation/platform/applications/cache/cache-settings/) of the Application holds how long a response stays in cache. It then sets the inputs that make two requests different, in its own `modules.application_accelerator` object. How a variation changes the cache key, with its diagram, is on the [Application Accelerator overview](/en/documentation/platform/applications/application-accelerator/#request-path). +When the response to one URL depends on a cookie, a device, or a request body, the cache has to tell those requests apart. In an [Application](/en/documentation/platform/applications/), adding those inputs to the cache key requires [Application Accelerator](/en/documentation/platform/applications/application-accelerator/), a Platform Resource that unlocks four capabilities for the cache and the rules. Application Accelerator is off in a new Application, and each Application turns it on separately, in the Application's `modules.application_accelerator.enabled` field in the API. -The sections cover what turning on Application Accelerator unlocks, what a variation costs, and how purges reach variations. The last section compares _Bypass Cache_ with a time to live (TTL) of 0. +A [cache setting](/en/documentation/platform/applications/cache/cache-settings/), the set of values that tell Cache how to store and serve a response and for how long, also holds the inputs that make two requests different, in its own `modules.application_accelerator` object. How a variation changes the cache key, with its diagram, is on the [Application Accelerator overview](/en/documentation/platform/applications/application-accelerator/#request-path). + +The sections cover what turning on Application Accelerator unlocks, what a variation costs, and how purges reach the copies that variations create. The last section compares _Bypass Cache_ with a time to live (TTL) of 0. --- @@ -21,12 +23,14 @@ Turning on Application Accelerator unlocks four capabilities that look unrelated - Cache variation by query string, by cookie, by device group, and by request method, through [Advanced Cache Key](/en/documentation/platform/applications/cache/cache-settings/#application-accelerator), a Feature of Application Accelerator. - Caching of `POST` and `OPTIONS` responses, beyond the `GET` and `HEAD` responses an Application caches without it. -- A Max Age as low as 0 seconds, in the `modules.cache.max_age` field of a cache setting, under the 60-second floor that holds without it. +- A Max Age under the 60-second floor, in the `modules.cache.max_age` field of a cache setting. - More [Rules Engine](/en/documentation/platform/applications/rules-engine/) behaviors, and the `${request_uri}` and `${device_group}` variables in rule criteria. The behaviors are _Add Request Cookie_ and _Add Response Cookie_, _Bypass Cache_, _Capture Match Groups_, _Filter Request Cookie_ and _Filter Response Cookie_, _Forward Cookies_, and _Rewrite Request_. -What the four have in common is dynamic content. Cache variation gives the cache key the extra input it needs to tell two correct responses apart. Caching `POST` and `OPTIONS` responses extends the cache past `GET` and `HEAD`, and a `POST` carries that input in its request body. A TTL under a minute fits content that stops being correct before a minute passes. Several of the gated behaviors act on the cookies and paths that carry the difference in the first place. +What the four have in common is dynamic content. Cache variation gives the cache key the extra input it needs to tell two correct responses apart. Caching `POST` and `OPTIONS` responses extends the cache past `GET` and `HEAD`, and a `POST` carries that input in its request body. + +A TTL under a minute fits content that stops being correct before a minute passes. Several of the gated behaviors act on the cookies and paths that carry the difference in the first place. -Application Accelerator is all four or none. An Application takes cache variation only together with the other three capabilities. The API refuses a cache setting that sets a variation on an Application with Application Accelerator off. For the error the API returns, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#errors). +Application Accelerator is all four or none. The API refuses a cache setting that sets a variation on an Application with Application Accelerator off. For the error the API returns, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#errors). Turning on Application Accelerator leaves traffic as it was: the query-string, cookie, and device controls of a cache setting start at `ignore`, and the method list starts empty. A cache setting reaches a request only when a [Set Cache Policy](/en/documentation/platform/applications/rules-engine/#set-cache-policy) behavior applies that cache setting. @@ -36,33 +40,41 @@ Turning on Application Accelerator can generate usage-related costs. For more in ## The cost of a variation -Cache variation costs storage first. The cost follows from how the key is built: each distinct value of a varying attribute produces a separate cached object. That makes the choice of what to vary by more consequential than the choice to vary at all. A cookie whose value is unique to each visitor gives every visitor a copy of the object. The cache still works, but each stored response then serves a single visitor. The number of objects grows with the audience instead of with the content. +Cache variation costs storage first. The cost follows from how the key is built: each distinct value of a varying attribute produces a separate copy of the response. That makes the choice of what to vary by more consequential than the choice to vary at all. + +A cookie whose value is unique to each visitor gives every visitor a copy of the response. The cache still works, but each stored copy then serves a single visitor. The number of copies grows with the audience instead of with the content. + +An allowlist is the control for that cost. The `allowlist` behavior names the query-string arguments or the cookies that change the response, so only an attribute it names can create another copy. The `all` behavior varies by every query-string argument or cookie the request carries. -An allowlist is the control for that cost. The `allowlist` behavior names the query-string arguments or the cookies that change the response, so only an attribute it names can create another object. The `all` behavior varies by every query-string argument or cookie the request carries. For example, a link that arrives with a campaign argument gets its own cached object under `all`. Under an allowlist that does not name that argument, the same link maps to the shared object. +For example, a link that arrives with a campaign argument gets a separate copy under `all`. Under an allowlist that does not name that argument, the same link maps to the shared copy. -Sorting applies the same economy to the order of the arguments. The chosen arguments enter the key in the order the request submitted them, so `?a=1&b=2` and `?b=2&a=1` are two objects that hold one response. With `sort_enabled` on, those variations group under one key, ordered alphabetically. For example, a product listing that changes with its `category` and `page` arguments names both in an allowlist. With `sort_enabled` on, every order of the two arguments reaches one object. The cost of sorting is that the key then differs from the URL as the client wrote it, which matters at purge time. For the Console steps that set these controls, refer to [Configure Advanced Cache Key for an application](/en/documentation/guides/application-performance/cache-and-purge/advanced-cache-key/). +Sorting applies the same economy to the order of the arguments. The chosen arguments enter the key in the order the request submitted them, so `?a=1&b=2` and `?b=2&a=1` are two copies of one response. With `sort_enabled` on, every order of the arguments groups under one key, sorted alphabetically. + +For example, a product listing that changes with its `category` and `page` arguments names both in an allowlist. With `sort_enabled` on, every order of the two arguments reaches one copy. + +The cost of sorting is that the key then differs from the URL as the client wrote it, which matters at purge time. For the Console steps that set these controls, refer to [Configure Advanced Cache Key for an application](/en/documentation/guides/application-performance/cache-and-purge/advanced-cache-key/). --- ## Cache variation and purges -A purge is a request that removes an object from the cache, and it finds the object by its cache key. A URL purge converts the URL it receives to a cache key without considering content variation. So every variation that the URL does not carry survives it, such as a cookie variation or a device group variation, and its copies stay in the cache. +A purge is a request that removes an object from the cache, and it finds the object by its cache key. A URL purge converts the URL it receives to a cache key without considering content variation. So the copies that a cookie variation or a device group variation creates survive it, because the URL does not carry those inputs. -Two purge types reach them. A cache key purge names each variation, and a wildcard purge ends the key with `@@*`. Query-string variations are the exception, because the query string is part of the URL. A URL purge reaches them when the arguments are sent in the order they were presented, or in alphabetical order when `sort_enabled` is on. +Two purge types reach those copies. A cache key purge names the key of each copy, and a wildcard purge ends the key with `@@*`. Query-string variations are the exception, because the query string is part of the URL. A URL purge reaches their copies when the arguments are sent in the order they were presented, or in alphabetical order when `sort_enabled` is on. -The variations you configure are also the objects a purge has to reach. So a variation with many distinct values costs you at purge time as well as in storage. For the purge types and the steps to run each one, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#purge-content-that-varies). +Each copy that a variation creates is also an object a purge has to reach. So a variation with many distinct values costs you at purge time as well as in storage. For the purge types and the steps to run each one, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#purge-content-that-varies). --- ## Bypass Cache and a TTL of 0 -Without Application Accelerator, the shortest Max Age that a cache setting accepts, in its `modules.cache.max_age` field, is 60 seconds, and the API refuses a lower value. For the error, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#errors). Application Accelerator removes that floor and allows 0 seconds, or 3 seconds when the cache setting also has [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) on. A TTL of 0 differs from not caching, and that difference is why both exist. Both need Application Accelerator, because _Bypass Cache_ is one of the behaviors it unlocks. +Without Application Accelerator, the `modules.cache.max_age` field of a cache setting accepts no value below 60 seconds. For the error the API returns, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#errors). Application Accelerator removes that floor and allows 0 seconds, or 3 seconds when the cache setting also has [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) on. -The [Bypass Cache](/en/documentation/platform/applications/rules-engine/#bypass-cache) behavior sends every HTTP and HTTPS request its rule matches to the origin, and the response bypasses Azion's own cache. It leaves the browser cache as a _Set Cache Policy_ behavior sets it. Its effect also stops at Azion's own cache: an Application with active Tiered Cache settings keeps caching objects in the Tiered Cache layer for the Max Age of the cache setting. Use it when each request has to receive different content. +A TTL of 0 differs from not caching, and that difference is why both exist. Both need Application Accelerator, because _Bypass Cache_ is one of the behaviors it unlocks. -A Max Age of 0 seconds keeps the request on the cache path: the response carries a cache key and reports `MISS`, and every request still reaches the origin. +The [Bypass Cache](/en/documentation/platform/applications/rules-engine/#bypass-cache) behavior sends every HTTP and HTTPS request its rule matches to the origin, and the response bypasses Azion's own cache. It leaves the browser cache as a _Set Cache Policy_ behavior sets it. Its effect also stops at Azion's own cache: an Application with active Tiered Cache settings keeps caching objects in the Tiered Cache layer for the Max Age of the cache setting. Use it when each request has to receive different content. -Both send every request to the origin. The difference is the cache path: a TTL of 0 keeps the request on it, and _Bypass Cache_ keeps the response out of Azion's cache. +A Max Age of 0 seconds also sends every request to the origin, but it keeps the request on the cache path: the response carries a cache key and reports `MISS`. _Bypass Cache_ keeps the response out of Azion's cache instead. --- @@ -70,7 +82,7 @@ Both send every request to the origin. The difference is the cache path: a TTL o - The controls behind cache variation, cached POST and OPTIONS responses, and a TTL under the floor. + The controls behind cache variation, cached POST and OPTIONS responses, and a TTL under the 60-second floor. The Console steps that set the variation controls of a cache setting, including Sort. The steps that turn on caching for POST and OPTIONS responses. Application Accelerator turned on and a first cache setting that varies. diff --git a/apps/docs/src/content/docs/en/pages/build/application-accelerator/overview.mdx b/apps/docs/src/content/docs/en/pages/build/application-accelerator/overview.mdx index 5b68aa2dc3..7c04adea7c 100644 --- a/apps/docs/src/content/docs/en/pages/build/application-accelerator/overview.mdx +++ b/apps/docs/src/content/docs/en/pages/build/application-accelerator/overview.mdx @@ -1,6 +1,6 @@ --- title: Application Accelerator -description: Vary the cache key by query string, cookie, device group, or method with Application Accelerator, and cache one copy per variation. +description: Vary the cache key by query string, cookie, device group, or method with Application Accelerator, and cache a separate copy for each value. meta_tags: 'application accelerator, cache variation, cache key, advanced cache key, query string, cookies, device groups, post and options caching, bypass cache, applications' namespace: documentation_products_application_acceleration permalink: /documentation/platform/applications/application-accelerator/ @@ -10,27 +10,18 @@ import DocButton from '~/components/webkit/DocButton.vue' import DocCardGroup from '@aziontech/webkit/doc-card-group' import DocCard from '@aziontech/webkit/doc-card' -**Application Accelerator** is a Platform Resource that unlocks four capabilities for the cache and the rules of an [Application](/en/documentation/platform/applications/). With Application Accelerator on, an Application can add more parts of the request to the cache key, cache `POST` and `OPTIONS` responses, and keep a response in cache for less than 60 seconds. Its rules can also use more [Rules Engine](/en/documentation/platform/applications/rules-engine/) behaviors, such as _Bypass Cache_ and _Forward Cookies_, and two more variables. - -A cache files each stored response under a key built from the request. When that key holds only the URL, every visitor who requests the URL gets the same copy, even when the content changes with a cookie, a device, or an argument. Adding one of those inputs to the key gives each of its values a copy of its own. One URL then holds several correct responses, and each visitor receives the one that matches their request. - -In an Application with Application Accelerator on, the key can take four inputs: a query-string argument, a cookie, the device group, and the request method. A [device group](/en/documentation/platform/applications/device-groups/) is a name and a regular expression that the Application compares with the `User-Agent` header of each request. - -Application Accelerator is off in a new Application, and each Application turns it on separately, in the Application's `modules.application_accelerator.enabled` field in the API. Each [cache setting](/en/documentation/platform/applications/cache/cache-settings/) of the Application holds how long a response stays in cache. It also sets which inputs vary the key, in its own `modules.application_accelerator` object. Then a [rule](/en/documentation/platform/applications/rules-engine/) with the [Set Cache Policy](/en/documentation/platform/applications/rules-engine/#set-cache-policy) behavior applies the cache setting to the requests the rule matches. Use Application Accelerator to cache separate copies of a page personalized by a cookie, an API response that changes with its query string, a catalog that differs by device, or a `POST` response. +**Application Accelerator** is a Platform Resource that unlocks four cache and rule capabilities on Azion's distributed infrastructure, for the requests received by an [Application](/en/documentation/platform/applications/). With it, an Application can vary the cache key by query string, cookie, [device group](/en/documentation/platform/applications/device-groups/), or request method, and cache `POST` and `OPTIONS` responses. Its cache settings accept a shorter minimum time to live (TTL), and its rules can use [Rules Engine](/en/documentation/platform/applications/rules-engine/) behaviors and variables reserved to Application Accelerator. Use Application Accelerator to cache a cookie-personalized page, a query-string API response, or a per-device catalog. - + --- ## Request path -A cache key is the index entry for a cached object. By default, Azion builds it from the scheme, the host, and the path of the request, so each path is one object in cache. Unless a cache setting varies the key by query string, every query string of a path maps to that one object. Each variation a cache setting turns on adds one input to the key, and each kind appends its own marker: +Turning on Application Accelerator leaves every cache key as it was: a variation applies only through a [Set Cache Policy](/en/documentation/platform/applications/rules-engine/#set-cache-policy) rule. That rule applies the cache setting that holds the variation to the requests it matches. A [cache setting](/en/documentation/platform/applications/cache/cache-settings/), the set of values that tell [Cache](/en/documentation/platform/applications/cache/) how to store and serve a response and for how long, holds its variations in its own `modules.application_accelerator` object. -- A cookie variation appends the `@@` separator, then the names and values of the cookies, each followed by `;`. -- A device variation appends `@@` and the name of the device group. -- A cached `POST` response appends `@@` and the MD5 hash of the request body. A cached `OPTIONS` response adds only its method prefix. -- A query-string variation under `allowlist` or `denylist`, the `behavior` values that name the arguments to keep or to leave out, appends `@@`, then `?` and the chosen arguments. Under `all`, which varies the key by every argument, the whole query string follows the path, before `@@`. +A cache key is the index entry for a cached object. By default, Azion builds it from the scheme, the host, and the path of the request, so each path is one object in cache. Unless a cache setting varies the key by query string, every query string of a path maps to that one object. Each variation a cache setting turns on appends its input to the key with a marker, as [Cache keys](/en/documentation/platform/applications/cache/cache-keys/#key-format) details. A request that uses any method other than `GET` or `HEAD` is a complex request, and its key carries the method as a prefix. @@ -58,61 +49,13 @@ flowchart TD 1. The request reaches the Application with its scheme, host, path, and query string. 2. A _Set Cache Policy_ rule applies a cache setting to the request. -3. The key starts with the scheme, the host, and the path. Each variation in the cache setting's `modules.application_accelerator` object then appends its input, with the marker that this section lists for it. -4. When [Cache](/en/documentation/platform/applications/cache/) holds a valid copy under that key, that copy becomes the response. +3. Cache builds the key from the request and from each variation in the cache setting. +4. When Cache holds a valid copy under that key, that copy becomes the response. 5. Otherwise, the [Connector](/en/documentation/platform/connectors/) routes the request to the origin server, and Cache stores the response under that key. -A cookie variation on a `user` cookie produces a key shaped like `httpwww.example.com/@@user=user;`. For a cached `POST`, the key is shaped like `posthttpsdynamic.example.com/path@@md5_of_post_body`. Two requests share a cached object when they produce the same key, and they get separate objects when they do not. For the full format and every input a key carries, refer to [Cache keys](/en/documentation/platform/applications/cache/cache-keys/#key-format). - -For what turning on Application Accelerator unlocks, the cost of a variation, and purges, refer to [Cache variation](/en/documentation/platform/applications/application-accelerator/cache-variation/). That page also compares _Bypass Cache_ with a time to live (TTL) of 0. - ---- - -## Cache setting structure - -A cache setting holds the inputs that vary the cache key in its `modules.application_accelerator` object, which [Azion Console](https://console.azion.com/) shows as the **Application Accelerator** section of the setting only while Application Accelerator is on in the Application. This cache setting keeps a product listing for 30 seconds and gives each value of its `category` argument a copy of its own. Send it as the body of `POST /v4/workspace/applications//cache_settings`: - -```json -{ - "name": "product-listing", - "browser_cache": { "behavior": "honor" }, - "modules": { - "cache": { - "behavior": "override", - "max_age": 30 - }, - "application_accelerator": { - "cache_vary_by_querystring": { - "behavior": "allowlist", - "fields": ["category"], - "sort_enabled": true - } - } - } -} -``` - -- `modules.application_accelerator` holds the four variation controls: `cache_vary_by_querystring`, `cache_vary_by_cookies`, `cache_vary_by_devices`, and `cache_vary_by_method`. A control the body leaves out keeps its default, `ignore`, or an empty list for the methods. -- `behavior` takes `ignore`, `all`, `allowlist`, or `denylist`, and the device control takes `ignore` or `allowlist`. Here, `allowlist` varies the key only by the arguments in `fields`, and `sort_enabled` groups every order of them under one key. -- `max_age` set to `30` is accepted only while Application Accelerator is on. Without it, the floor is 60 seconds, and [Azion API](https://api.azion.com/) refuses a lower value with `21021`. -- The Application carries a `modules.application_accelerator` object of its own, and its `enabled` field turns Application Accelerator on. `PATCH /v4/workspace/applications/` sets it with `{ "modules": { "application_accelerator": { "enabled": true } } }`. While that field is `false`, the API refuses with `21013` a cache setting that varies the cache: a query-string, cookie, or device-group variation whose `behavior` is not `ignore`, or a method in `cache_vary_by_method`. - -If you configured a `Vary` header or a cache-key rule elsewhere, the model transfers. You name the inputs that make two requests different, and each distinct value gets its own copy. Only the four variation controls set those inputs, so a request header such as `Accept-Language` cannot vary the key. - ---- - -## Scope and limits +Two requests share a copy when they produce the same key, and they get separate copies when they do not. -- **Application**: Application Accelerator is off in a new Application, and it belongs to the Application, so one Application can have it on while another has it off. Turning it on leaves traffic as it was: the controls of a cache setting start at `ignore`, and a cache setting reaches a request only through a [Set Cache Policy](/en/documentation/platform/applications/rules-engine/#set-cache-policy) rule. [Main Settings](/en/documentation/platform/applications/main-settings/#platform-resources) shows where to turn it on in Azion Console and the API. -- **What Application Accelerator unlocks**: cache variation, the caching of `POST` and `OPTIONS` responses, and a Max Age, the cache setting's `modules.cache.max_age` field, as low as 0 seconds. It also unlocks Rules Engine behaviors and the `${request_uri}` and `${device_group}` variables, and an Application takes all of these or none. The behaviors are _Add Request Cookie_ and _Add Response Cookie_, _Bypass Cache_, _Capture Match Groups_, _Filter Request Cookie_ and _Filter Response Cookie_, _Forward Cookies_, and _Rewrite Request_. An Application passes `POST`, `PUT`, `PATCH`, `DELETE`, and `OPTIONS` to the origin with or without Application Accelerator. Of those methods, Application Accelerator makes only the `POST` and `OPTIONS` responses cacheable. -- **Variation size**: each distinct value of a varied input is a separate cached object. A cookie unique to each visitor gives every visitor a copy, so the number of objects grows with the audience instead of with the content. For how an allowlist and sorting, the `sort_enabled` field, bound that number, refer to [Cache variation](/en/documentation/platform/applications/application-accelerator/cache-variation/#the-cost-of-a-variation), and for the practices, to [Applications best practices](/en/documentation/platform/applications/best-practices/#application-accelerator). -- **Purges**: cookie and device group variations survive a URL purge. A cache key purge reaches them, and so does a wildcard purge that ends the key with `@@*`. Query-string variations are the exception. A URL purge reaches them when it sends the arguments in the order they were presented, or in alphabetical order with `sort_enabled` on. For the purge types, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#purge-content-that-varies). -- **Bypass Cache and a TTL of 0**: [Bypass Cache](/en/documentation/platform/applications/rules-engine/#bypass-cache) sends each request that its rule matches to the origin and keeps the response out of Azion's cache. It acts on Azion's cache only, so the [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) layer keeps caching objects for an Application whose cache settings turn Tiered Cache on. A Max Age of 0 seconds keeps the request on the cache path, and every request still reaches the origin. For how the two compare, refer to [Bypass Cache and a TTL of 0](/en/documentation/platform/applications/application-accelerator/cache-variation/#bypass-cache-and-a-ttl-of-0). -- **Neighbors**: with Application Accelerator on, the variation controls of a cache setting decide what goes into a key, and [Cache](/en/documentation/platform/applications/cache/) then keeps a separate copy for each value. To vary the cache on the `ims` string of [Image Processor](/en/documentation/platform/applications/image-processor/), add `ims` to the query-string allowlist of the cache setting that serves images. -- **Interfaces**: you turn on Application Accelerator in Azion Console, through Azion API at `/v4/workspace/applications/`, and with `azion update application --application-accelerator` in [Azion CLI](/en/documentation/devtools/cli/). [`azion.config.js`](/en/documentation/devtools/cli/azion-config-js/) sets it with `applicationAcceleratorEnabled`, and [Azion Lib](/en/documentation/devtools/azion-lib/application/) with `application_acceleration` on an update. [Azion Terraform Provider](/en/documentation/devtools/terraform/) manages the Application resource that carries the switch. The variation controls belong to the cache setting, at `/v4/workspace/applications//cache_settings` or through `azion create cache-setting` flags such as `--cache-by-query-string` and `--cache-by-cookies`. `azion create cache-setting` takes device-group variation and the cache Max Age only in a `--file` body. -- **Observability**: with `Pragma: azion-debug-cache` on a request, the `x-cache-key` header of the response shows what each variation added to the key. A `POST` reports `-` in `x-cache` until the `cache_vary_by_method` field of the cache setting carries `post`. To check the cache status of one response, refer to [Check the cache status of a response](/en/documentation/guides/application-performance/cache-and-purge/check-page-cache-time/). -- **Limits**: with Application Accelerator on, the Max Age of a cache setting goes down to 0 seconds, or to 3 seconds when the cache setting also has Tiered Cache on. Turning it on can generate usage-related costs. For each TTL bound and the answer past it, refer to [Applications limits](/en/documentation/platform/applications/limits/#application-accelerator), and for the rates, to [Pricing](/en/documentation/fundamentals/pricing/#application-accelerator). [Azion pricing](https://www.azion.com/en/pricing/) lists what each plan includes. -- **Terms**: the [Applications glossary](/en/documentation/platform/applications/glossary/) defines the words the Application Accelerator pages give a specific meaning, such as Advanced Cache Key, cache variation, and device group. +For what turning on Application Accelerator unlocks, the cost of a variation, and purges, refer to [Cache variation](/en/documentation/platform/applications/application-accelerator/cache-variation/). That page also compares _Bypass Cache_ with a TTL of 0. --- @@ -120,9 +63,11 @@ If you configured a `Vary` header or a cache-key rule elsewhere, the model trans - + - - + + + + diff --git a/apps/docs/src/content/docs/en/pages/build/application-accelerator/quickstart.mdx b/apps/docs/src/content/docs/en/pages/build/application-accelerator/quickstart.mdx index 7356516080..39fe47f248 100644 --- a/apps/docs/src/content/docs/en/pages/build/application-accelerator/quickstart.mdx +++ b/apps/docs/src/content/docs/en/pages/build/application-accelerator/quickstart.mdx @@ -18,14 +18,14 @@ This guide instructs you through your first cache setting that varies the cache - Turn on [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) on an Application. - Create a [cache setting](/en/documentation/platform/applications/cache/cache-settings/) that holds the listing for 30 seconds and varies by the `category` argument. -- Add a Rules Engine rule that applies the cache setting to requests for `/products`. +- Add a [Rules Engine](/en/documentation/platform/applications/rules-engine/) rule that applies the cache setting to requests for `/products`. - Request the listing twice, with two values of `category`, and read the cache key of each response. Three parts of the Application produce that result, and each one depends on the one before it: -1. Application Accelerator is on or off in each Application separately. It unlocks the fields that vary the cache key, and it removes the 60-second floor on the cache TTL. +1. Application Accelerator is on or off in each Application separately. It unlocks the fields that vary the cache key, and it removes the 60-second floor on the Max Age, the cache time to live (TTL). 2. A cache setting belongs to the Application and holds the cache behavior, the Max Age, and the variation. It sets what the cache does, not which requests it does it to. -3. The [Rules Engine](/en/documentation/platform/applications/rules-engine/) rule applies the cache setting with the [Set Cache Policy](/en/documentation/platform/applications/rules-engine/#set-cache-policy) behavior. Its criteria decide which requests the cache setting covers. +3. The Rules Engine rule applies the cache setting with the [Set Cache Policy](/en/documentation/platform/applications/rules-engine/#set-cache-policy) behavior. Its criteria decide which requests the cache setting covers. A cache setting reaches a request only when a rule applies that cache setting, so creating one leaves traffic as it was. @@ -45,7 +45,7 @@ A cache setting reaches a request only when a rule applies that cache setting, s ### Console - An Azion account. To create one, refer to [How to create an account on Azion](/en/documentation/fundamentals/creating-account/). -- The **Edit Applications** permission on the account. It grants permission to edit, create, and remove Applications, and it also requires the permission **View Applications**. Refer to [Teams permissions](/en/documentation/fundamentals/teams-permissions/). +- The **Edit Applications** permission on the account. It grants permission to edit, create, and remove Applications, and it also requires the permission **View Applications**. For more information, refer to [Teams permissions](/en/documentation/fundamentals/teams-permissions/). - An Application that receives the requests of a Workload, with a path whose response changes with a query string argument. This guide uses the `/products` path and the `category` argument. To create both, refer to [Applications quickstart](/en/documentation/platform/applications/quickstart/). - Access to Azion Console. To sign in, refer to [Access Azion Console](/en/documentation/guides/platform/account-and-billing/how-to-access-azion-console/). - `curl`, to request the listing. @@ -57,7 +57,7 @@ A cache setting reaches a request only when a rule applies that cache setting, s ### CLI - An Azion account. To create one, refer to [How to create an account on Azion](/en/documentation/fundamentals/creating-account/). -- The **Edit Applications** permission on the account. It grants permission to edit, create, and remove Applications, and it also requires the permission **View Applications**. Refer to [Teams permissions](/en/documentation/fundamentals/teams-permissions/). +- The **Edit Applications** permission on the account. It grants permission to edit, create, and remove Applications, and it also requires the permission **View Applications**. For more information, refer to [Teams permissions](/en/documentation/fundamentals/teams-permissions/). - An Application that receives the requests of a Workload, with a path whose response changes with a query string argument. This guide uses the `/products` path and the `category` argument. To create both, refer to [Applications quickstart](/en/documentation/platform/applications/quickstart/). - The [Azion CLI](/en/documentation/devtools/cli/) installed and authorized. - `curl`, to request the listing. @@ -69,7 +69,7 @@ A cache setting reaches a request only when a rule applies that cache setting, s ### API - An Azion account. To create one, refer to [How to create an account on Azion](/en/documentation/fundamentals/creating-account/). -- The **Edit Applications** permission on the account. It grants permission to edit, create, and remove Applications, and it also requires the permission **View Applications**. Refer to [Teams permissions](/en/documentation/fundamentals/teams-permissions/). +- The **Edit Applications** permission on the account. It grants permission to edit, create, and remove Applications, and it also requires the permission **View Applications**. For more information, refer to [Teams permissions](/en/documentation/fundamentals/teams-permissions/). - An Application that receives the requests of a Workload, with a path whose response changes with a query string argument. This guide uses the `/products` path and the `category` argument. To create both, refer to [Applications quickstart](/en/documentation/platform/applications/quickstart/). - A [personal token](/en/documentation/guides/platform/account-and-billing/personal-tokens/) and `curl`. @@ -193,7 +193,7 @@ Turning on Application Accelerator can generate usage-related costs. For more in ## Create a cache setting that varies by query string -The cache setting holds the cache behavior and the variation. The Max Age of `30` seconds that this stage sets is the point of the exercise. Without Application Accelerator, the shortest cache TTL an Application accepts is 60 seconds. +The cache setting holds the cache behavior and the variation. This stage sets a Max Age of `30` seconds, which only Application Accelerator allows: without it, the shortest Max Age an Application accepts is 60 seconds. @@ -204,21 +204,36 @@ The cache setting holds the cache behavior and the variation. The Max Age of `30 To create the cache setting in Azion Console: + + + Access [Azion Console](https://console.azion.com/) > **Applications** > your Application. + + - Enter a value in **Name**. For example: `product-listing`. + In **Name**, enter a value. For example: `product-listing`. - + - Under **Cache**, select _Override cache behavior_ and set **Max Age** to `30`. + Under **Cache**, select _Override cache behavior_. - + - Under **Application Accelerator**, open **Cache vary by Query String** and set **Behavior** to _Allowlist_. + In **Max Age**, enter `30`. + + + + + Under **Application Accelerator**, select **Cache vary by Query String**. + + + + + Set **Behavior** to _Allowlist_. @@ -234,7 +249,7 @@ To create the cache setting in Azion Console: -The cache setting appears in the **Cache Settings** tab. It holds an object for 30 seconds and gives each value of `category` its own cached object. +The cache setting appears in the **Cache Settings** tab. It holds a copy for 30 seconds and gives each value of `category` a separate copy. @@ -281,7 +296,9 @@ The cache setting appears in the **Cache Settings** tab. It holds an object for - --cache-setting-id 123462 --format json`} /> + Replace `` with the id that the create command printed: + + --cache-setting-id --format json`} /> This excerpt of the output carries the fields the file set: @@ -307,7 +324,7 @@ The cache setting appears in the **Cache Settings** tab. It holds an object for -The cache setting holds an object for 30 seconds and gives each value of `category` its own cached object. Record the id: the rule in the next stage selects the cache setting by it. For every flag the command accepts, refer to [`azion create cache-setting`](/en/documentation/devtools/cli/resources/cache-setting/#create). +The cache setting holds a copy for 30 seconds and gives each value of `category` a separate copy. Record the id: the rule in the next stage selects the cache setting by it. For every flag the command accepts, refer to [`azion create cache-setting`](/en/documentation/devtools/cli/resources/cache-setting/#create). @@ -371,12 +388,12 @@ To create the cache setting with the Azion API, replace `[TOKEN VALUE]` with you } ``` - A `max_age` below 60 is accepted only while Application Accelerator is on. + A `max_age` below 60 seconds is accepted only while Application Accelerator is on. -The cache setting holds an object for 30 seconds and gives each value of `category` its own cached object. Record the `id`: the rule in the next stage selects the cache setting by it. +The cache setting holds a copy for 30 seconds and gives each value of `category` a separate copy. Record the `id`: the rule in the next stage selects the cache setting by it. @@ -397,11 +414,16 @@ A cache setting reaches a request only when a rule applies that cache setting. To apply the cache setting to the listing path in Azion Console: + + + Access [Azion Console](https://console.azion.com/) > **Applications** > your Application. + + - Enter a name for the rule. For example: `Cache the product listing`. + In **Name**, enter a name for the rule. For example: `Cache the product listing`. @@ -441,12 +463,12 @@ The rule applies the cache setting to every request whose URI starts with `/prod ### CLI -To add the rule with the Azion CLI, send the body from a file, so the shell leaves `${uri}` as written. +The body goes in a file, so the shell leaves `${uri}` as written. To add the rule with the Azion CLI: - Save the following as `rule.json`, with the id of your cache setting in `attributes.value`: + Save the following as `rule.json`, and replace `` with the id of your cache setting: } } ] }`} /> @@ -491,12 +513,12 @@ The rule applies the cache setting to every request whose URI starts with `/prod ### API -To add the rule with the Azion API, replace `[TOKEN VALUE]` with your personal token and `` with the ID of your Application. Send the body from a file, so the shell leaves `${uri}` as written. +The body goes in a file, so the shell leaves `${uri}` as written. Replace `[TOKEN VALUE]` with your personal token and `` with the ID of your Application. To add the rule with the Azion API: - Save the following as `rule.json`, with the `id` the cache setting create returned in `attributes.value`: + Save the following as `rule.json`, and replace `` with the `id` that the cache setting create returned: } } ] }`} /> @@ -549,7 +571,7 @@ A new rule can take a few minutes to propagate. Wait before you request the path ## Read the cache key -Azion returns the cache key of an object when the request carries the Azion debug header `Pragma: azion-debug-cache`. Reading that key for two values of `category` shows the variation the cache setting created. +Azion returns the cache key of an object when the request carries the Azion debug header `Pragma: azion-debug-cache`. Reading that key for two values of `category` shows the separate copies that the variation creates. Your Application receives the requests of a Workload, and that Workload answers on its workload domain, in the format `xxxxxxxxx.map.azionedge.net`. To add a custom domain to that Workload, refer to [Add a custom domain to a workload](/en/documentation/guides/platform/migration/configure-a-domain/). @@ -576,16 +598,16 @@ The argument changed, so the key changed with it: x-cache-key: httpswww.example.com/products@@?category=hats ``` -Two keys are two cached objects, which is what the allowlist asked for. For the full format of a cache key, refer to [Cache key format](/en/documentation/platform/applications/cache/cache-keys/#key-format). +Two keys are two separate copies, which is what the allowlist asked for. For the full format of a cache key, refer to [Cache key format](/en/documentation/platform/applications/cache/cache-keys/#key-format). -Your Application now caches the `/products` listing for 30 seconds and keeps one object per value of `category`. +Your Application now caches the `/products` listing for 30 seconds and keeps a separate copy for each value of `category`. --- ## Next steps - + diff --git a/apps/docs/src/content/docs/en/pages/build/application-accelerator/settings.mdx b/apps/docs/src/content/docs/en/pages/build/application-accelerator/settings.mdx index 4686371a05..9d952406d3 100644 --- a/apps/docs/src/content/docs/en/pages/build/application-accelerator/settings.mdx +++ b/apps/docs/src/content/docs/en/pages/build/application-accelerator/settings.mdx @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -[Application Accelerator](/en/documentation/platform/applications/application-accelerator/) is a Platform Resource that unlocks four capabilities for the cache and the rules of an [Application](/en/documentation/platform/applications/). The capabilities are cache variation, the caching of `POST` and `OPTIONS` responses, a Max Age below 60 seconds, and the [Rules Engine](/en/documentation/platform/applications/rules-engine/) behaviors and variables that this page lists. Each Application turns Application Accelerator on separately. This page carries the name, the type, and the default of each field, and the interface that sets it. +[Application Accelerator](/en/documentation/platform/applications/application-accelerator/) is a Platform Resource that unlocks four capabilities for the cache and the rules of an [Application](/en/documentation/platform/applications/). The capabilities are cache variation, the caching of `POST` and `OPTIONS` responses, a Max Age below 60 seconds, and the [Rules Engine](/en/documentation/platform/applications/rules-engine/) behaviors and variables that this page lists. Each Application turns Application Accelerator on separately. --- @@ -28,9 +28,21 @@ Application Accelerator is off in a new Application, and the setting belongs to | [`azion.config.js`](/en/documentation/devtools/cli/azion-config-js/) | The `AzionApplication` object | `applicationAcceleratorEnabled` | | [Azion Lib](/en/documentation/devtools/azion-lib/application/) | The data passed to an Application update, because API v3 refuses the field on create | `application_acceleration` | -`modules.application_accelerator.enabled` is a boolean and defaults to `false`. `applicationAcceleratorEnabled` and `application_acceleration` are booleans, and the Azion CLI flag takes a string. +`modules.application_accelerator.enabled` is a boolean and defaults to `false`. `applicationAcceleratorEnabled` and `application_acceleration` are booleans, and the Azion CLI flag takes a string. In API v4, this body on `PATCH /v4/workspace/applications/{id}` turns it on: -The [Azion Terraform Provider](/en/documentation/devtools/terraform/) manages the Application resource that carries the switch. Turning on Application Accelerator can generate usage-related costs. For more information, refer to [Pricing](/en/documentation/fundamentals/pricing/#application-accelerator). +```json +{ + "modules": { + "application_accelerator": { + "enabled": true + } + } +} +``` + +The [Azion Terraform Provider](/en/documentation/devtools/terraform/) manages the Application resource that carries the switch. + +Turning on Application Accelerator can generate usage-related costs. For more information, refer to [Pricing](/en/documentation/fundamentals/pricing/#application-accelerator). --- @@ -38,7 +50,7 @@ The [Azion Terraform Provider](/en/documentation/devtools/terraform/) manages th Every cache setting carries its own `modules.application_accelerator` object, which shares its name with the object of the Application. The Application's object holds only `enabled`, and the cache setting's object holds the variations. With Application Accelerator on in the Application, the fields of the cache setting's object can leave their defaults. -Those fields configure Advanced Cache Key, a Feature of Application Accelerator. They decide which parts of a request, besides its scheme, host, and path, produce a separate cached object. A cookie, device group, or cached `POST` variation appends the `@@` separator to the cache key, and so does a query-string variation under `allowlist` or `denylist`, as `@@?` and its arguments. Under `all`, the whole query string follows the path, before `@@`. A cached `OPTIONS` response adds only the `options` prefix, with no `@@`. For the format of a cache key, refer to [Cache key format](/en/documentation/platform/applications/cache/cache-keys/#key-format). +Those fields configure Advanced Cache Key, a Feature of Application Accelerator. They decide which parts of a request, besides its scheme, host, and path, produce a separate copy in the cache. For the marker that each variation appends to the cache key, refer to [Cache key format](/en/documentation/platform/applications/cache/cache-keys/#key-format). Each field maps to a control in the **Application Accelerator** section of a cache setting, in Azion Console, which shows that section only while Application Accelerator is on in the Application: @@ -47,7 +59,7 @@ Each field maps to a control in the **Application Accelerator** section of a cac | `cache_vary_by_method` | array of enum, at most 2 values: `options`, `post` | `[]` | **Cache vary by Method**, one checkbox per method | The request methods whose responses are cached. | | `cache_vary_by_querystring.behavior` | enum: `ignore`, `all`, `allowlist`, `denylist` | `ignore` | **Cache vary by Query String** > **Behavior** | The mode that decides how the query string varies the key. | | `cache_vary_by_querystring.fields` | array of string | `[]` | **Cache vary by Query String** > **Fields** | The query string arguments the mode applies to. | -| `cache_vary_by_querystring.sort_enabled` | boolean | `false` | **Cache vary by Query String** > **Sort** | Whether the variations group under one key, ordered alphabetically. | +| `cache_vary_by_querystring.sort_enabled` | boolean | `false` | **Cache vary by Query String** > **Sort** | Whether every order of the arguments groups under one key, sorted alphabetically. | | `cache_vary_by_cookies.behavior` | enum: `ignore`, `all`, `allowlist`, `denylist` | `ignore` | **Cache vary by Cookies** > **Behavior** | The mode that decides how cookies vary the key. | | `cache_vary_by_cookies.cookie_names` | array of string | `[]` | **Cache vary by Cookies** > **Fields** | The cookies the mode applies to. | | `cache_vary_by_devices.behavior` | enum: `ignore`, `allowlist` | `ignore` | **Cache vary by Devices** > **Behavior** | The mode that decides how device groups vary the key. | @@ -55,15 +67,41 @@ Each field maps to a control in the **Application Accelerator** section of a cac In Azion Console, the **Behavior** dropdowns of **Cache vary by Query String** and **Cache vary by Cookies** show _Allowlist_, _Denylist_, _Ignore_, and _All_. The one of **Cache vary by Devices** shows _Allowlist_ and _Ignore_. -`allowlist` and `denylist` on the query string need at least one argument in `fields`, or the API returns error `21018`. While Application Accelerator is off in the Application, the API refuses a variation with error `21013`. For every error a cache setting returns, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#errors). +Only these four controls set the inputs that vary the key, so a request header such as `Accept-Language` cannot vary it. + +`allowlist` and `denylist` on the query string need at least one argument in `fields`, or the API returns error `21018`. While Application Accelerator is off in the Application, the API refuses with error `21013` a cache setting that varies the cache: a query-string, cookie, or device-group `behavior` other than `ignore`, or a method in `cache_vary_by_method`. For every error a cache setting returns, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#errors). + +This cache setting keeps a product listing for 30 seconds and gives each value of its `category` argument a separate copy. Send it as the body of `POST /v4/workspace/applications/{application_id}/cache_settings`: + +```json +{ + "name": "product-listing", + "browser_cache": { "behavior": "honor" }, + "modules": { + "cache": { + "behavior": "override", + "max_age": 30 + }, + "application_accelerator": { + "cache_vary_by_querystring": { + "behavior": "allowlist", + "fields": ["category"], + "sort_enabled": true + } + } + } +} +``` + +A control that the body leaves out keeps its default, `ignore`, or an empty list for the methods. One field on the same cache setting sits outside that object and still requires Application Accelerator: | Field | Type | Default | Console control | What it sets | | --- | --- | --- | --- | --- | -| `modules.cache.max_age` | integer, `0` to `31536000` seconds | `60` | **Cache** > **Max Age** | How long the cache holds the object. A value below 60 requires Application Accelerator. | +| `modules.cache.max_age` | integer, `0` to `31536000` seconds | `60` | **Cache** > **Max Age** | How long the cache holds the object. A value below 60 seconds requires Application Accelerator. | -Without Application Accelerator, a `max_age` below 60 returns error `21021`. With Application Accelerator and Tiered Cache on, a value below 3 returns error `21020`. +Without Application Accelerator, a `max_age` below 60 seconds returns error `21021`. With Application Accelerator and Tiered Cache on, a value below 3 seconds returns error `21020`. For the ceilings that bound a cache setting, refer to [Limits](/en/documentation/platform/applications/limits/#application-accelerator). @@ -111,13 +149,13 @@ These Rules Engine behaviors require Application Accelerator on the Application | Behavior | Phases | What it does | | --- | --- | --- | | [Add Request Cookie, Add Response Cookie](/en/documentation/platform/applications/rules-engine/#add-request-cookie-and-add-response-cookie) | Request, Response | Adds a cookie to the `Set-Cookie` header. | -| [Bypass Cache](/en/documentation/platform/applications/rules-engine/#bypass-cache) | Request | Stops Azion's cache from storing the origin response, and leaves the browser cache untouched. | -| [Capture Match Groups](/en/documentation/platform/applications/rules-engine/#capture-match-groups) | Request, Response | Stores a regular expression capture over a request field in a temporary variable. | +| [Bypass Cache](/en/documentation/platform/applications/rules-engine/#bypass-cache) | Request | Sends the request to the origin and keeps the response out of Azion's cache. | +| [Capture Match Groups](/en/documentation/platform/applications/rules-engine/#capture-match-groups) | Request, Response | Stores the groups a regular expression captures from a request field in a temporary array. | | [Filter Request Cookie, Filter Response Cookie](/en/documentation/platform/applications/rules-engine/#filter-request-cookie) | Request, Response | Removes a cookie from the request to the origin or the response to the user. | | [Forward Cookies](/en/documentation/platform/applications/rules-engine/#forward-cookies) | Request | Forwards the `Set-Cookie` header of the origin to users, including on a cache hit. | | [Rewrite Request](/en/documentation/platform/applications/rules-engine/#rewrite-request) | Request | Modifies the resource path requested from the origin. | -_Bypass Cache_ acts on Azion's cache and not on the [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) layer. An Application whose cache settings have Tiered Cache on keeps caching objects there for the Max Age of the cache setting. +_Bypass Cache_ leaves the browser cache untouched. It acts on Azion's cache and not on the [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) layer. An Application whose cache settings have Tiered Cache on keeps caching objects there for the Max Age of the cache setting. Rule criteria can read `${request_uri}` and `${device_group}`, and both require Application Accelerator. A rule that reads `${request_uri}` without it is refused with `25047`. For the variables, refer to [Variables](/en/documentation/platform/applications/rules-engine/#variables), and for the groups `${device_group}` matches, refer to [Device Groups](/en/documentation/platform/applications/device-groups/). @@ -131,7 +169,7 @@ Rule criteria can read `${request_uri}` and `${device_group}`, and both require - How each of these fields changes the cache key, and what a variation costs. + What Application Accelerator unlocks, what a variation costs, and how a purge reaches its copies. Turn on Application Accelerator and create a cache setting that varies the cache key. The ceilings that bound the values in these tables. How to purge an object that varies by cookie, query string, or device group. diff --git a/apps/docs/src/content/docs/en/pages/build/applications/best-practices.mdx b/apps/docs/src/content/docs/en/pages/build/applications/best-practices.mdx index 2979f14af0..103b413300 100644 --- a/apps/docs/src/content/docs/en/pages/build/applications/best-practices.mdx +++ b/apps/docs/src/content/docs/en/pages/build/applications/best-practices.mdx @@ -14,7 +14,7 @@ import DocItem from '@aziontech/webkit/doc-item' Most mistakes in the layer between your users and your origin stay invisible until a user meets one. A visitor sees a page you already replaced, or the origin answers requests that a stored copy could have answered. A session cookie reaches a user it was never issued to, or an image arrives heavier or cropped differently than the page asked. -The cause is rarely one wrong value. More often, a [cache key](/en/documentation/platform/applications/cache/cache-keys/), the string Azion files a stored copy under, varies by something the response ignores. Or one time to live (TTL) covers content that changes at different rates, or a change is judged before anyone reads the response. +The cause is rarely one wrong value. More often, a [cache key](/en/documentation/platform/applications/cache/cache-keys/), the index entry Cache stores a copy under, varies by something the response ignores. Or one time to live (TTL) covers content that changes at different rates, or a change is judged before anyone reads the response. These practices apply to an [Application](/en/documentation/platform/applications/) and its [device groups](/en/documentation/platform/applications/device-groups/). They also cover the [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) rules that act on its traffic, and the cache settings those rules apply. [How Applications works](/en/documentation/platform/applications/how-it-works/) explains the mechanisms behind them, and [Applications limits](/en/documentation/platform/applications/limits/) holds the value of every bound. For the practices of the Functions that an Application runs, refer to [Functions best practices](/en/documentation/platform/functions/best-practices/). @@ -36,7 +36,7 @@ The cost is coverage: a device of the class whose header carries none of the wor By default, an Application with [WebSocket Proxy](/en/documentation/platform/applications/websocket/) turned on proxies every request that carries `Upgrade: websocket` and `Connection: upgrade` to the origin as a WebSocket connection, whatever its path. Control those headers in the application you build, and send them only where the WebSocket protocol should be used. -The decision then lives in your client code. The same client also reopens a connection that closes. Azion recycles keepalive connections approximately every 15 minutes, which can close an active WebSocket connection. +The decision then lives in your client code. The same client also reopens a connection that closes. Azion recycles keepalive connections approximately every 15 minutes, which can close an active WebSocket connection, as [Applications limits](/en/documentation/platform/applications/limits/) lists. A connection that opens returns `101 Switching Protocols`, and any other status, even a `2xx` or a `3xx`, means the upgrade did not complete. For the headers and the statuses, refer to [WebSocket Proxy](/en/documentation/platform/applications/websocket/#upgrade-headers). @@ -44,13 +44,13 @@ A connection that opens returns `101 Switching Protocols`, and any other status, ## Cache -A cache setting belongs to one Application and holds how long Azion and the browser keep a response, and what makes two requests different. Kept too long, a copy shows a visitor content the origin already replaced. Kept too briefly, it sends the origin requests that a stored copy could have answered. +A cache setting is a set of values that tell Cache how to store and serve a response. It belongs to one Application and holds how long Azion and the browser keep a response, and what makes two requests different. Kept too long, a copy shows a visitor content the origin already replaced. Kept too briefly, it sends the origin requests that a stored copy could have answered. -These practices apply to the [cache settings](/en/documentation/platform/applications/cache/cache-settings/) of an Application and to the rules that apply those cache settings through the _Set Cache Policy_ behavior. They cover, in order, the TTL, the name of an object, the purge of its variations, Tiered Cache, stale cache, and the cache status of a response. The first practice shows a complete cache setting in the form the API accepts, and later practices name only the field they change. The last practice shows how to confirm each change in the response. +These practices apply to the [cache settings](/en/documentation/platform/applications/cache/cache-settings/) of an Application and to the rules that apply those cache settings through the _Set Cache Policy_ behavior. They cover, in order, the TTL, the name of an object, the purge of its copies, Tiered Cache, stale cache, and the cache status of a response. The first practice shows a complete cache setting in the form the API accepts, and later practices name only the field they change. The last practice shows how to confirm each change in the response. ### Match each TTL to how often its content changes -Under the `override` behavior, the Max Age of a cache setting sets the TTL of a copy, in its `modules.cache.max_age` field. A longer TTL answers more requests but lags further behind the origin. Assets can change only when a deployment replaces them, while a page changes through the day, so one TTL misfits part of the content. +Under _Override cache behavior_ (`override`), the Max Age of a cache setting sets the TTL of a copy, in its `modules.cache.max_age` field. A longer TTL answers more requests but lags further behind the origin. Assets can change only when a release replaces them, while a page changes through the day, so one TTL misfits part of the content. Give each group of paths that changes at one rate its own cache setting and rule. This setting keeps the assets 86,400 seconds in the browser and 300 seconds at Azion: @@ -68,22 +68,22 @@ Pages edited during the day get a second setting and rule, with a lower Max Age. ### Change an object's name when its content changes -An object that keeps its name needs a purge of every cache layer and variation each time its content changes. Put a version in the file name instead. The cache treats each version as a separate object, and the first request for it fetches the current bytes from the origin. Any scheme serves, such as a counter, a timestamp, or a content hash, provided different content always gets a different name: `https://static.example.com/assets/image_1.jpg` becomes `https://static.example.com/assets/image_2.jpg`. +An object that keeps its name needs a purge of every cache layer and copy each time its content changes. Put a version in the file name instead. The cache treats each version as a separate object, and the first request for it fetches the current bytes from the origin. Any scheme serves, such as a counter, a timestamp, or a content hash, provided different content always gets a different name: `https://static.example.com/assets/image_1.jpg` becomes `https://static.example.com/assets/image_2.jpg`. -An update reaches users without a purge, and a browser that holds the earlier name keeps a valid object. Both versions stay available, so a rollback points your pages at the previous name. The cost is that every reference to the object changes with it, which a build step can automate and a hand edit cannot. +An update reaches users without a purge, and a browser that holds the earlier name keeps a valid object. Both versions stay available, so a rollback points your pages at the previous name. The cost is that every reference to the object changes with it, which a build step can automate and a hand edit cannot. The first response for the new name reports `MISS` in `x-cache`, as [Read the cache status after every cache change](/en/documentation/platform/applications/best-practices/#read-the-cache-status-after-every-cache-change) shows. ### Purge an object that varies by cache key or wildcard -[Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/) finds a copy by its cache key, and an object that varies has one key per variation. A URL purge converts the URL into one key. A copy that varies by cookie, device group, or image format survives it, while the purge reports success. +[Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/) finds a copy by its cache key, and an object that varies has one key per copy. A URL purge converts the URL into one key. A copy that varies by cookie, device group, or image format survives it, while the purge reports success. -Name those keys in a cache key purge, up to 50 per request, or reach them with a wildcard. These [Azion CLI](/en/documentation/devtools/cli/) commands send both, the wildcard ending in `@@*` for cookie variations: +Name those keys in a cache key purge, up to 50 per request as [Applications limits](/en/documentation/platform/applications/limits/#real-time-purge) lists, or reach them with a wildcard. These [Azion CLI](/en/documentation/devtools/cli/) commands send both, the wildcard ending in `@@*` for cookie variations: ```bash azion purge --cachekey "httpwww.example.com/@@user=user;" azion purge --wildcard "www.example.com/@@*" ``` -Each command prints `Purge carried out successfully`. A variation with many values costs more to purge and to store, so choose its purge when you choose the variation. For the purge that reaches each variation, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#purge-content-that-varies). For the steps, refer to [Purge cached content](/en/documentation/guides/application-performance/cache-and-purge/purge-cached-content/). +Each command prints `Purge carried out successfully`. A variation with many values costs more to purge and to store, so choose its purge when you choose the variation. For the purge that reaches each copy, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#purge-content-that-varies). For the steps, refer to [Purge cached content](/en/documentation/guides/application-performance/cache-and-purge/purge-cached-content/). ### Keep Tiered Cache for long-lived objects with a stable body @@ -95,7 +95,9 @@ The layer is outside the reach of a _Bypass Cache_ rule, as [Rule out Tiered Cac ### Turn on stale cache where an old page is better than an error -With stale cache on in a cache setting, Azion serves a copy past its TTL when revalidating it with the origin fails. It does so for the origin's `stale-while-revalidate` value under the `honor` behavior, and for 300 seconds otherwise. The visitor gets the last good version rather than an error page. Set `modules.cache.stale_cache.enabled` to `true` for an article, a listing, or a product page. Keep it off for a price or an availability figure that a visitor decides on. +With stale cache on in a cache setting, Azion serves a copy past its TTL when revalidating it with the origin fails. It does so for the origin's `stale-while-revalidate` value under _Honor cache policies_ (`honor`), and for 300 seconds otherwise. The visitor gets the last good version rather than an error page. + +Set `modules.cache.stale_cache.enabled` to `true` for an article, a listing, or a product page. Keep it off for a price or an availability figure that a visitor decides on. A response served this way reports `STALE` in `x-cache`. For the length of the window, what makes a revalidation fail, and when a purge serves better than expiry, refer to [Expiration and freshness](/en/documentation/platform/applications/cache/expiration-and-freshness/#stale-cache). @@ -115,9 +117,9 @@ One response describes one copy on one server, so repeat the request before you ## Application Accelerator -Every attribute a cache key varies by multiplies the copies Azion keeps of one URL, one copy per value. When the attribute leaves the response unchanged, those copies carry identical bytes, split the traffic between them, and add keys a purge has to reach. +Application Accelerator lets a cache setting vary the cache key. Every attribute the key varies by multiplies the copies Azion keeps of one URL, one copy per value. When the attribute leaves the response unchanged, those copies carry identical bytes, split the traffic between them, and add keys a purge has to reach. -[Application Accelerator](/en/documentation/platform/applications/application-accelerator/settings/) unlocks Rules Engine behaviors such as _Bypass Cache_ and _Forward Cookies_, and it lets a cache setting change the fields of its `modules.application_accelerator` object. While it is off in the Application, the API refuses with `21013` a variation in those fields, a `behavior` other than `ignore` or a method in `cache_vary_by_method`. +[Application Accelerator](/en/documentation/platform/applications/application-accelerator/settings/) unlocks Rules Engine behaviors such as _Bypass Cache_ and _Forward Cookies_, and it lets a cache setting change the fields of its `modules.application_accelerator` object. While it is off in the Application, the API refuses with `21013` any variation in those fields: a `behavior` other than `ignore`, or a method in `cache_vary_by_method`. The first four practices shape the key: the query string, its order, the cookies, and the session cookies under _Forward Cookies_. `x-cache-key` shows what each of them adds, as [Read the cache status after every cache change](/en/documentation/platform/applications/best-practices/#read-the-cache-status-after-every-cache-change) explains. The last one concerns _Bypass Cache_ and the Tiered Cache layer it leaves untouched. @@ -146,23 +148,23 @@ An empty list is refused with `21018`. Leave off an argument that changes the re Unsorted, the listed arguments join the cache key in the order the client wrote them. `?category=shoes&page=2` and `?page=2&category=shoes` then become two copies of the same response. With `sort_enabled` set to `true` in the same `cache_vary_by_querystring` object, the arguments enter the key in alphabetical order, and both requests land on one copy. -The cost shows at purge time: a URL purge reaches the copy only when it names the arguments in alphabetical order. When the Azion CLI creates a cache setting, only `--file` and a JSON body set `sort_enabled`. On an update, `--enable-caching-string-sort` sets it. To see which purge reaches each variation, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#purge-content-that-varies). +The cost shows at purge time: a URL purge reaches the copy only when it names the arguments in alphabetical order. With the Azion CLI, only `--file` sets `sort_enabled` on a create, and `--enable-caching-string-sort` sets it on an update, as [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#application-accelerator) lists. To see which purge reaches each copy, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#purge-content-that-varies). ### List only the cookies that segment content -Browsers send every cookie they hold for a domain, and few of them change what the origin returns. Under `all`, an analytics identifier or a consent flag joins the key, and copies multiply with cookie values rather than with content. Under `allowlist`, only the cookies you name vary the key, which is how an Application segments content by user profile or another grouping. +Browsers send every cookie they hold for a domain, and few of them change what the origin returns. Under `all`, an analytics identifier or a consent flag joins the key, and copies multiply with cookie values rather than with content, up to one copy per visitor for a cookie unique per visitor. Under `allowlist`, only the cookies you name vary the key, which is how an Application segments content by user profile or another grouping. -Use the allowlist when cookies manage user sessions: `behavior` set to `allowlist` and `session_id` in `cookie_names`, under `modules.application_accelerator.cache_vary_by_cookies`. The cost is copies: a cookie unique per visitor means one copy per visitor. For the steps, refer to [Configure Advanced Cache Key for an application](/en/documentation/guides/application-performance/cache-and-purge/advanced-cache-key/). +Name in `cookie_names` only the cookies that change the response, with `behavior` set to `allowlist`. For the steps, refer to [Configure Advanced Cache Key for an application](/en/documentation/guides/application-performance/cache-and-purge/advanced-cache-key/). ### Allowlist session cookies where Forward Cookies runs -The [Forward Cookies](/en/documentation/platform/applications/rules-engine/#forward-cookies) behavior passes the origin's `Set-Cookie` header on to users, cache hits included. A cached response can then hand one user the `Set-Cookie` of another user's session. Name the session cookie in an allowlist, so each session gets its own key: `behavior` set to `allowlist`, with `session_id` in `cookie_names`. A `denylist` that names `session_id` leaves the cookie out of the key, and the sessions share one object. +The [Forward Cookies](/en/documentation/platform/applications/rules-engine/#forward-cookies) behavior passes the origin's `Set-Cookie` header on to users, cache hits included. A cached response can then hand one user the `Set-Cookie` of another user's session. Name the session cookie in an allowlist, so each session gets its own key: under `modules.application_accelerator.cache_vary_by_cookies`, `behavior` set to `allowlist`, with `session_id` in `cookie_names`. A `denylist` that names `session_id` leaves the cookie out of the key, and the sessions share one object. Put the allowlist on the cache setting that the Forward Cookies rule applies through _Set Cache Policy_. For the steps, refer to [Configure cache policies for an application](/en/documentation/guides/application-performance/cache-and-purge/cache-settings/#forward-cookies-from-the-origin-to-the-user). ### Rule out Tiered Cache before you rely on Bypass Cache -The [Bypass Cache](/en/documentation/platform/applications/rules-engine/#bypass-cache) behavior keeps Azion's cache from storing the origin's response, but the [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/#bypass-cache) layer is outside the rule's reach. While the rule is active, a layer that the cache settings turn on keeps caching objects for the Max Age of the cache setting, whose floor is 3 seconds with Tiered Cache on. The layer shows only in the cache settings, not in the rule, so a rule that looks right can still leave content cached. +The [Bypass Cache](/en/documentation/platform/applications/rules-engine/#bypass-cache) behavior sends the requests its rule matches to the origin and keeps the response out of Azion's cache. The [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/#bypass-cache) layer is outside the rule's reach. While the rule is active, a layer that the cache settings turn on keeps caching objects for the Max Age of the cache setting, whose floor is 3 seconds with Tiered Cache on. The layer shows only in the cache settings, not in the rule, so a rule that looks right can still leave content cached. When freshness is the requirement, look for `modules.cache.tiered_cache.enabled` set to `true` in the cache settings that cover the rule's paths. If no layer may keep a copy, decide on Tiered Cache together with the rule. For the symptom a missed layer produces and its fix, refer to [Content is still served from cache after a Bypass Cache rule](/en/documentation/platform/applications/troubleshooting/#content-is-still-served-from-cache-after-a-bypass-cache-rule). @@ -170,9 +172,15 @@ When freshness is the requirement, look for `modules.cache.tiered_cache.enabled` ## Image Processor -A transformed image can fail a page in three ways. The file outweighs what the page needs, or the crop removes something nobody meant to remove. Or the image arrives in a format the client cannot display. Around the transformation, the cache setting decides how derived images are stored and how often the same request reaches Image Processor again. +Image Processor transforms an image on request, and a transformed image can fail a page in three ways: + +- The file outweighs what the page needs. +- The crop removes something nobody meant to remove. +- The image arrives in a format the client cannot display. + +Around the transformation, the cache setting decides how derived images are stored and how often the same request reaches Image Processor again. -These practices apply to [Image Processor](/en/documentation/platform/applications/image-processor/settings/): the `ims` query string, the rule whose _Optimize Images_ behavior acts on that query string, and that rule's cache setting. The first three practices concern the request: its quality, its resize, and the `Accept` header. The last two concern the cache setting: its allowlist and its TTL. `x-cache` and `x-cache-key` show the result of those two, as [Read the cache status after every cache change](/en/documentation/platform/applications/best-practices/#read-the-cache-status-after-every-cache-change) explains. +These practices apply to [Image Processor](/en/documentation/platform/applications/image-processor/settings/): the `ims` parameter, the rule whose _Optimize Images_ behavior acts on that parameter, and that rule's cache setting. The first three practices concern the request: its quality, its resize, and the `Accept` header. The last two concern the cache setting: its allowlist and its TTL. `x-cache` and `x-cache-key` show the result of those two, as [Read the cache status after every cache change](/en/documentation/platform/applications/best-practices/#read-the-cache-status-after-every-cache-change) explains. ### Request quality 85 unless one image needs otherwise @@ -196,13 +204,13 @@ The API takes the behavior as `{ "type": "add_request_header", "attributes": { " `ims` carries the transformation, so it is an argument the response depends on. [Key the cache only on the arguments the response depends on](/en/documentation/platform/applications/best-practices/#key-the-cache-only-on-the-arguments-the-response-depends-on) applies to it. The cache setting that the image rule applies sets `fields` to `["ims"]` under an `allowlist`. -The difference is a second Platform Resource: `cache_vary_by_querystring` belongs to `modules.application_accelerator`, so this allowlist needs Application Accelerator, even though transforming an image does not. For the Azion Console controls that set the field, refer to [Image Processor settings](/en/documentation/platform/applications/image-processor/settings/#cache-variation). +This allowlist needs a second Platform Resource: `cache_vary_by_querystring` belongs to `modules.application_accelerator`, so the allowlist needs Application Accelerator, even though transforming an image does not. For the Azion Console controls that set the field, refer to [Image Processor settings](/en/documentation/platform/applications/image-processor/settings/#cache-variation). ### Keep derived images cached as long as their sources allow -Image Processor adds one image to the monthly Images meter for each request it processes, whether the request resizes, crops, converts, or filters it. A request the cache answers runs no transformation and adds nothing. A short Max Age sends the same request to Image Processor again on a timer unrelated to changes at the source. +Image Processor counts one processed image for each request it transforms, whether the request resizes, crops, converts, or filters the image. A request the cache answers runs no transformation and adds nothing to that count. A short Max Age sends the same request to Image Processor again on a timer unrelated to changes at the source. -Give the cache setting for derived images the longest `modules.cache.max_age` its source content tolerates, up to 31,536,000 seconds. The cost is freshness. A replaced source image leaves its derived versions, one key per processing and per format, cached until they expire or a purge removes them. For the images each plan includes, refer to [Azion pricing](https://www.azion.com/en/pricing/). +Give the cache setting for derived images the longest `modules.cache.max_age` its source content tolerates, up to the 31,536,000 seconds that [Applications limits](/en/documentation/platform/applications/limits/#cache) allows. The cost is freshness. A replaced source image leaves its derived versions, one key per processing and per format, cached until they expire or a purge removes them. For how processed images are billed, and the images each plan includes, refer to [Azion pricing](https://www.azion.com/en/pricing/). --- diff --git a/apps/docs/src/content/docs/en/pages/build/applications/glossary.mdx b/apps/docs/src/content/docs/en/pages/build/applications/glossary.mdx index e06ee8e2aa..a83e35c627 100644 --- a/apps/docs/src/content/docs/en/pages/build/applications/glossary.mdx +++ b/apps/docs/src/content/docs/en/pages/build/applications/glossary.mdx @@ -11,44 +11,44 @@ Definitions for the terms the [Applications](/en/documentation/platform/applicat | Term | Definition | | --- | --- | | Add Request Header | The [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) behavior that adds a header in the `Field: value` form to the request, in the Request Phase, `add_request_header` in the API. With `Accept: image/webp`, it makes the automatic conversion of Image Processor deliver WEBP to every request its rule matches. The API refuses the name `add_header` with `10039 Invalid Choice`. | -| Advanced Cache Key | A Feature of Application Accelerator that varies the cache key by parts of a request beyond the URL: the query string, cookies, device groups, and the request method. It needs Application Accelerator on in the Application, and each cache setting configures it in its `modules.application_accelerator` object, through the four Cache vary by controls. [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/#cache-variation) documents each control and where it sits in Azion Console and the API. | -| Application | The entity that runs its rules on the requests received by a [Workload](/en/documentation/platform/workloads/), once that Workload's deployment sets that Application. A new Application starts with Cache and Functions on, Application Accelerator and Image Processor off, and no rules. The **Application** field of a Workload's **Deployment Settings** in Azion Console sets it, the API serves your Applications at `/v4/workspace/applications`, and [Applications](/en/documentation/platform/applications/) documents the Platform Resource. | -| Application Accelerator | A Platform Resource nested in Applications that unlocks four capabilities for the cache and the rules of an Application: cache variation, the caching of `POST` and `OPTIONS` responses, a Max Age below 60 seconds, and the Rules Engine behaviors that Azion Console marks _- Required Application Accelerator_, with the `${request_uri}` and `${device_group}` variables. It is off in a new Application, `modules.application_accelerator.enabled` in the API, and with cache variation, a cache setting can add the query string, cookies, the device group, or the request method to the cache key. [Applications](/en/documentation/platform/applications/#application-accelerator) describes it, and the [Application Accelerator overview](/en/documentation/platform/applications/application-accelerator/#request-path) follows a request through it. | +| Advanced Cache Key | A Feature of Application Accelerator that varies the cache key by parts of a request beyond its scheme, host, and path: the query string, cookies, device groups, and the request method. It needs Application Accelerator on in the Application, and each cache setting configures it in its `modules.application_accelerator` object, through the four Cache vary by controls. [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/#cache-variation) documents each control and where it sits in Azion Console and the API. | +| Application | The entity that processes the requests received by a [Workload](/en/documentation/platform/workloads/), once that Workload's deployment sets that Application: it can run serverless functions, act as a reverse proxy for your origins, or combine the two. A new Application starts with Cache and Functions on, Application Accelerator and Image Processor off, and no rules. The API serves your Applications at `/v4/workspace/applications`, and [Applications](/en/documentation/platform/applications/) documents the Platform Resource. | +| Application Accelerator | A Platform Resource nested in Applications that unlocks four capabilities for the cache and the rules of an Application: cache variation, the caching of `POST` and `OPTIONS` responses, a Max Age below 60 seconds, and the Rules Engine behaviors that Azion Console marks _- Required Application Accelerator_, with the `${request_uri}` and `${device_group}` variables. It is off in a new Application, `modules.application_accelerator.enabled` in the API, and with cache variation, a cache setting can add the query string, cookies, the device group, or the request method to the cache key. The [Application Accelerator overview](/en/documentation/platform/applications/application-accelerator/#request-path) describes it and follows a request through it. | | autocrop | The centered crop that a `WidthxHeight` resize can apply so the derived image fills the requested box. The crop is vertical or horizontal, depending on how the original dimensions fit the requested ones, as [Image Processor URL parameters](/en/documentation/platform/applications/image-processor/url-parameters/#resize) shows. | -| behavior | The action a rule runs on the requests its criteria match, such as _Set Cache Policy_, _Set Connector_, or _Run Function_. A rule runs its behaviors in the order it lists them, a behavior that ends the processing stops the behaviors and rules after it in its phase, and [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) names the Platform Resource each behavior needs. On a cache setting, `behavior` is also the field of each Cache vary by control, and [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/#cache-variation) lists the values of each. | +| behavior | The action a rule runs on a request, or on a response, that matches its criteria, such as _Set Cache Policy_, _Set Connector_, or _Run Function_. A rule runs its behaviors in the order it lists them, a behavior that ends the processing stops the behaviors and rules after it in its phase, and [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) names the Platform Resource each behavior needs. On a cache setting, `behavior` is also the field of each Cache vary by control, and [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/#cache-variation) lists the values of each. | | Bypass Cache | The [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/#bypass-cache) behavior that sends a matching request to the origin and keeps the response out of Azion's cache, `bypass_cache` in the API. It runs in the Request Phase, requires Application Accelerator, leaves the browser cache to _Set Cache Policy_, and differs from a TTL of 0 seconds, as [Bypass Cache and a TTL of 0](/en/documentation/platform/applications/application-accelerator/cache-variation/#bypass-cache-and-a-ttl-of-0) explains. It acts on Azion's cache only, so an Application with active Tiered Cache settings keeps caching objects in the [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/#bypass-cache) layer for the Max Age of the cache setting. | -| Cache | A Platform Resource nested in Applications that stores copies of the responses to the requests received by an Application, to serve later requests for the same object from those copies. Each copy stays in the data center that stored it. It is always on in an Application: the API refuses `modules.cache.enabled` set to `false` with `31001`, and Azion Console shows the **Cache** switch locked on, with the note `Automatically enabled in all accounts.` [Applications](/en/documentation/platform/applications/#cache) describes it, and the [Cache overview](/en/documentation/platform/applications/cache/#request-path) follows a request through it. | -| cache key | The index entry under which Cache stores an object, case sensitive. In Cache, the default setting ignores the query string, so the key concatenates the scheme, host, and path, as in `httpsstatic.example.com/page/site.js`, and each variation adds a value after the `@@` separator: under `allowlist` and `denylist`, that value includes the query string arguments a setting names, but under `all`, the whole query string follows the path, before `@@`. When the cache setting that serves images names `ims` in its allowlist, the key carries the `ims` query string after `@@`, and a converted image carries its format at the end. Under the default setting, the `ims` value is not part of the key, so every size and processing of the path shares a key, and the first one stored answers every `ims` value; [Cache keys](/en/documentation/platform/applications/cache/cache-keys/#key-format) documents every form. | -| cache key purge | A [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#cache-key-purge) type, `cachekey` in the API, that clears the objects stored under each key of a list. A key can name one variation, by query string, cookie, or image format, so a purge of every variation of an object lists each key. It is the only purge type that reaches the [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/#purge) layer. | +| Cache | A Platform Resource nested in Applications that stores copies of the responses to the requests received by an Application, to serve later requests for the same object from those copies. Each copy stays in the data center that stored it. It is always on in an Application: the API refuses `modules.cache.enabled` set to `false` with `31001`, and Azion Console shows the **Cache** switch locked on, with the note `Automatically enabled in all accounts.` The [Cache overview](/en/documentation/platform/applications/cache/#request-path) describes it and follows a request through it. | +| cache key | The index entry under which Cache stores an object, case sensitive. The default key concatenates the scheme, host, and path, as in `httpsstatic.example.com/page/site.js`, and each variation a cache setting turns on adds to it, most of them after the `@@` separator. Under the default setting, the `ims` value is not part of the key, so every size and processing of a path shares one key; [Cache keys](/en/documentation/platform/applications/cache/cache-keys/#key-format) documents every form, the query string and `ims` cases included. | +| cache key purge | A [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#cache-key-purge) type, `cachekey` in the API, that clears the objects stored under each key of a list. A key can name one copy of an object that varies by query string, cookie, or image format, so a purge of every copy of the object lists each key. It is the only purge type that reaches the [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/#purge) layer. | | cache setting | A set of values that tell Cache how to store and serve a response: the TTLs of Azion's cache and of the browser, and the inputs that tell two requests apart. It belongs to one Application and carries Max Age, stale cache, Large File Optimization, and Tiered Cache, plus the four Cache vary by controls in its `modules.application_accelerator` object. It acts only through a rule that applies that cache setting with _Set Cache Policy_ to the requests the rule matches; [Cache settings](/en/documentation/platform/applications/cache/cache-settings/) documents every field, and [Cache quickstart](/en/documentation/platform/applications/cache/quickstart/) creates a first one. | | cache status | The state of a response in Cache, at the start of the `x-cache` header: `HIT`, `MISS`, `EXPIRED`, `STALE`, `UPDATING`, `REVALIDATED`, or `BYPASS`. A response that Azion does not store reports `-` while Application Accelerator is on, but with it off, a `GET` or `HEAD` response that is not stored reports `MISS`, with `x-cache-expires-in: 0`. [Cache keys](/en/documentation/platform/applications/cache/cache-keys/#cache-status) gives the meaning of each one. | -| cache variation | A further copy of an object stored under its own key because the request method, a query string argument, a cookie, a device group, an image format, or a byte range of a large file differs. While Application Accelerator is off in the Application, the API refuses a variation with `21013`, and that includes the query-string variation on `ims` that [Image Processor settings](/en/documentation/platform/applications/image-processor/settings/#cache-variation) describes. Image Processor processes an image whether Application Accelerator is on or off; [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/#cache-variation) documents the four controls. | -| Connector | The entity that routes the requests of an Application to your origin, once a rule sets the ID of that Connector in the _Set Connector_ behavior. It belongs to [Connectors](/en/documentation/platform/connectors/), the Platform Resource that replaces the origins that earlier versions of Applications configured on the Application. With [Load Balancer](/en/documentation/platform/connectors/load-balancer/) enabled, one Connector of the `http` type can spread traffic across several origins. | -| criterion | A single condition inside a rule: a variable such as `${uri}`, a comparison operator, and an argument when the operator takes one, sent in the API as `variable`, `operator`, `conditional`, and `argument`. Inside a group, criteria combine with `and` and `or`, and `and` takes precedence over `or`. The groups of a rule are joined by `and`, and the API carries them as an array of groups, `[[{...}]]`. [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) lists every variable and operator. | -| Debug Rules | The setting of an Application that logs the Rules Engine rules each request ran, `debug` in the API and off in a new Application. With it on, the rules that ran appear in the `$traceback` field in Data Stream and [Real-Time Events](/en/documentation/platform/real-time-events/), and in the `stacktrace` field of the [Real-Time Events GraphQL API](/en/documentation/devtools/graphql/gql-real-time-events-fields/). [Main Settings](/en/documentation/platform/applications/main-settings/#debug-rules) shows where to turn it on in Azion Console, and [Debug rules created with Rules Engine](/en/documentation/guides/application-development/getting-started/debug-rules/) shows how to read those logs. | +| cache variation | An input of a request beyond its scheme, host, and path that varies the cache key, so each value gets a separate copy: the request method, a query string argument, a cookie, a device group, an image format, or a byte range of a large file. While Application Accelerator is off in the Application, the API refuses a variation with `21013`, and that includes the query-string variation on `ims` that [Image Processor settings](/en/documentation/platform/applications/image-processor/settings/#cache-variation) describes. Image Processor processes an image whether Application Accelerator is on or off; [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/#cache-variation) documents the four controls. | +| Connector | The entity that holds the address of your origin and the settings Azion uses to reach it, and routes the requests of an Application there once a rule sets the ID of that Connector in the _Set Connector_ behavior. It belongs to [Connectors](/en/documentation/platform/connectors/), the Platform Resource that replaces the origins that earlier versions of Applications configured on the Application. With [Load Balancer](/en/documentation/platform/connectors/load-balancer/) enabled, one Connector of the `http` type can spread traffic across several origins. | +| criterion | A single condition inside a rule: a variable such as `${uri}`, a comparison operator, and an argument when the operator takes one, sent in the API as `variable`, `operator`, `conditional`, and `argument`. Inside a group, criteria combine with `and` and `or`, with `and` taking precedence, while the groups of a rule are joined by `and` and travel in the API as an array of groups, `[[{...}]]`. [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) lists every variable and operator. | +| Debug Rules | The setting of an Application that logs the Rules Engine rules each request runs, `debug` in the API and off in a new Application. With it on, the rules that ran appear in the `$traceback` field in Data Stream and [Real-Time Events](/en/documentation/platform/real-time-events/), and in the `stacktrace` field of the [Real-Time Events GraphQL API](/en/documentation/devtools/graphql/gql-real-time-events-fields/). [Main Settings](/en/documentation/platform/applications/main-settings/#debug-rules) shows where to turn it on in Azion Console, and [Debug rules created with Rules Engine](/en/documentation/guides/application-development/getting-started/debug-rules/) shows how to read those logs. | | derived image | The image that Image Processor builds from the source image on the origin. Image Processor returns it without saving it as an asset of the account, and the source image stays unchanged. The [Image Processor overview](/en/documentation/platform/applications/image-processor/#request-path) describes how a request produces one. | -| device group | A name and a regular expression that an Application compares with the `User-Agent` header of each request. A request belongs to the group when its header matches the expression. Each device group belongs to one Application, and a rule tests it through the `${device_group}` variable, which requires Application Accelerator. [Cache vary by Devices](/en/documentation/platform/applications/application-accelerator/settings/#cache-variation) varies the cache key by it, and [Device Groups](/en/documentation/platform/applications/device-groups/) documents the matching. | +| device group | A name and a regular expression that an Application compares with the `User-Agent` header of each request, and a request belongs to the group when its header matches the expression. Each device group belongs to one Application, and a rule tests it through the `${device_group}` variable, which requires Application Accelerator. [Cache vary by Devices](/en/documentation/platform/applications/application-accelerator/settings/#cache-variation) varies the cache key by it, and [Device Groups](/en/documentation/platform/applications/device-groups/) documents the matching. | | filter | The `ims` component that transforms an image beyond a resize or a crop, written `filters:name(argument)`, as in `filters:quality(15)`. One `ims` string combines several filters, separated by `:`. [Image Processor URL parameters](/en/documentation/platform/applications/image-processor/url-parameters/) documents `rotate`, `quality`, `watermark`, `format`, and `fill`. | | `fit-in` | The `ims` prefix that fits the derived image inside a `WidthxHeight` box and keeps the aspect ratio of the source image, as in `?ims=fit-in/400x400`. An image smaller than the box keeps its original size. Both dimensions are optional, and [Image Processor URL parameters](/en/documentation/platform/applications/image-processor/url-parameters/#resize) shows each form. | | Forward Cookies | The [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) behavior that sends the `Set-Cookie` header of the origin to the user even when the response comes from cache. It runs in the Request Phase and requires Application Accelerator. | | Function Instance | The entity that binds one of your [Functions](/en/documentation/platform/functions/) to one Application or one [Firewall](/en/documentation/platform/firewall/), with the arguments it runs with. The API serves the Function Instances of an Application at `/v4/workspace/applications//functions`, and a rule with the _Run Function_ behavior invokes a Function Instance by its ID in `attributes.value`. [Function Instances](/en/documentation/platform/applications/functions-instances/) documents its fields. | -| Image Processor | A Platform Resource nested in Applications that builds a new image, the derived image, from an image on the origin of an Application. It is off in a new Application, and each Application turns it on separately, in `modules.image_processor.enabled` in the API or with `--image-processor` in Azion CLI. [Applications](/en/documentation/platform/applications/#image-processor) describes it, and the [Image Processor overview](/en/documentation/platform/applications/image-processor/#request-path) follows a request through it. | +| Image Processor | A Platform Resource nested in Applications that builds a derived image from an image on the origin, for the requests an Application receives. It is off in a new Application, and each Application turns it on separately, in `modules.image_processor.enabled` in the API or with `--image-processor` in Azion CLI. The [Image Processor overview](/en/documentation/platform/applications/image-processor/#request-path) describes it and follows a request through it. | | `ims` | The query string parameter that tells Image Processor which transformation to apply, as in `?ims=400x`. It can sit anywhere in the query string, and an `ims` value that Image Processor cannot parse returns the source image without a transformation. [Image Processor URL parameters](/en/documentation/platform/applications/image-processor/url-parameters/#position-of-the-ims-parameter) documents every value it accepts and its position. | | Large File Optimization | A Feature of Cache that stores a large object as fragments of 1,024 kB, off by default and turned on per cache setting in `modules.cache.large_file_cache.enabled`. Azion caches each fragment when a user requests it, under its own cache key ending in `@@bytes=-`, and the Feature applies to Tiered Cache too when that layer is on. [Expiration and freshness](/en/documentation/platform/applications/cache/expiration-and-freshness/#large-file-optimization) describes the mechanism. | -| Main Settings | The set of values that apply to an Application as a whole: its name, the Platform Resources turned on in it, whether it logs the rules each request runs, and whether it is active. Azion Console groups them in the **Main Settings** tab of the Application, in four sections: **General**, which carries the name, **Modules**, **Debug Rules**, and **Status**. Delivery and protocol settings belong to the [Workload](/en/documentation/platform/workloads/) that receives the requests, not to Main Settings. [Main Settings](/en/documentation/platform/applications/main-settings/) documents each section. | +| Main Settings | The set of values that apply to an Application as a whole: its name, the Platform Resources turned on in it, whether it logs the rules each request runs, and whether it is active. Delivery and protocol settings belong to the [Workload](/en/documentation/platform/workloads/) that receives the requests, not to Main Settings. [Main Settings](/en/documentation/platform/applications/main-settings/) documents each section. | | Max Age | The cache setting field for how many seconds Azion's cache keeps a copy of an object, `modules.cache.max_age` in the API, with a default of `60` in Azion Console, the API, and the CLI. The API refuses a value below 60 with `21021` while Application Accelerator is off, a value below 3 with `21020` while Application Accelerator and Tiered Cache are both on, and a value above `31536000` with `10068`. The browser cache has a Max Age of its own, `browser_cache.max_age`; [Applications limits](/en/documentation/platform/applications/limits/#application-accelerator) carries the bounds that depend on the Platform Resources turned on. | -| `modules` | The API object that carries the switches of an Application, `application_accelerator`, `cache`, `functions`, and `image_processor`, each with an `enabled` value. Azion Console renders it as the **Modules** section of [Main Settings](/en/documentation/platform/applications/main-settings/#platform-resources), whose **Default Modules** are the same four, beside a **Subscription modules** group with a **Contact sales** action. Tiered Cache is not one of these switches: each cache setting turns it on in its own `modules.cache.tiered_cache.enabled` field. | +| `modules` | The API object that carries the switches of an Application, `application_accelerator`, `cache`, `functions`, and `image_processor`, each with an `enabled` value, as [Main Settings](/en/documentation/platform/applications/main-settings/#platform-resources) documents. Tiered Cache is not one of these switches: each cache setting turns it on in its own `modules.cache.tiered_cache.enabled` field. | | Optimize Images | The [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) behavior that applies Image Processor to the requests its rule matches, `optimize_images` in the API. It runs in the Request Phase, takes no arguments, and requires Image Processor on in the Application. The API accepts it alone in a rule, with no _Set Cache Policy_ beside it. | | phase | One of the two stages in which an Application runs rules: the Request Phase, on the request before a response exists, and the Response Phase, on the response delivered to the user. You set the phase of a rule when you create it, and you cannot change it later, so a rule in the other phase is a new rule. Caching is decided in the Request Phase, and [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) lists the phases each variable and behavior is available in. | -| Real-Time Purge | A Platform Resource that removes cached objects from Cache or Tiered Cache before their TTL ends. Once an object is in neither Cache nor Tiered Cache, the next request for it fetches the current version from the origin. A purge names its objects by URL, by cache key, or by a wildcard expression, and Azion queues it and lists it in the purge history once it completes. [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/) documents the three types and the layer each one reaches. | +| Real-Time Purge | A Platform Resource nested in Cache that removes cached objects from Cache, or from the Tiered Cache layer, before their TTL ends. Once an object is in neither layer, the next request for it fetches the current version from the origin. A purge names its objects by URL, by cache key, or by a wildcard expression, and [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/) documents the three types, the layer each one reaches, and how Azion queues a purge and lists it in the purge history once it completes. | | rule | An entry in Rules Engine for Applications that runs its behaviors, in one phase, on the requests its criteria match. Each rule carries a name and its phase, rules run in the order you arrange them, and a new Application has none. The API serves the rules of the Request Phase at `/v4/workspace/applications//request_rules` and those of the Response Phase at `/v4/workspace/applications//response_rules`, and [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) lists their fields. | -| Rules Engine for Applications | A Feature of Applications that holds the rules of an Application. The Application runs them in order as if-then logic, with the criteria as the if and the behaviors as the then. Azion Console shows it as the **Rules Engine** tab of each Application, with the rules grouped by phase. [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) documents every variable, operator, and behavior. | -| Run Function | The [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) behavior that invokes a Function Instance on the requests its rule matches, `run_function` in the API with the Function Instance ID in `attributes.value`. It runs in the Request Phase and in the Response Phase, which accepts only Functions written in Lua, and it needs Functions on in the Application, `modules.functions.enabled` in the API. [Function Instances](/en/documentation/platform/applications/functions-instances/#run-function-behavior) documents how it references the Function Instance. | +| Rules Engine for Applications | A Feature of Applications that holds the rules of an Application. The Application runs them in order as if-then logic, with the criteria as the if and the behaviors as the then. [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) documents every variable, operator, and behavior. | +| Run Function | The [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) behavior that invokes a Function Instance on what its rule matches, `run_function` in the API with the Function Instance ID in `attributes.value`. It runs in the Request Phase and in the Response Phase, which accepts only Functions written in Lua, and it needs Functions on in the Application, `modules.functions.enabled` in the API. [Function Instances](/en/documentation/platform/applications/functions-instances/#run-function-behavior) documents how it references the Function Instance. | | Set Cache Policy | The [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/#set-cache-policy) behavior that applies a cache setting to a matching request, `set_cache_policy` in the API with the cache setting ID in `attributes.value`. It runs in the Request Phase and works with Application Accelerator on or off. A cache setting acts only through a rule that carries this behavior, and the API refuses to delete a setting in use with `21014 Cannot Delete Cache Setting`. | -| Set Connector | The [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) behavior that routes the requests its rule matches to a [Connector](/en/documentation/platform/connectors/), `set_connector` in the API with the Connector ID in `attributes.value`. It runs in the Request Phase, and when more than one matching rule carries it, only the last one runs. | +| Set Connector | The [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) behavior that sends the requests its rule matches to a [Connector](/en/documentation/platform/connectors/), `set_connector` in the API with the Connector ID in `attributes.value`. It runs in the Request Phase, and when more than one matching rule carries it, only the last one runs. | | source image | The image file on the origin that Image Processor reads to build a derived image. Image Processor reads it without changing it, and each transformation yields a separate derived image. The [Image Processor overview](/en/documentation/platform/applications/image-processor/#request-path) describes the path between the two. | | stale cache | A Feature of Cache that can answer with an expired copy during a stale window, when a revalidation attempt with the origin fails. Each cache setting turns it on in `modules.cache.stale_cache.enabled`, and the window is the `stale-while-revalidate` value of the origin under _Honor cache policies_, or 300 seconds under _Override cache behavior_ or when the origin omits the directive, as [Expiration and freshness](/en/documentation/platform/applications/cache/expiration-and-freshness/#stale-cache) describes. | -| Tiered Cache | A Feature of Cache that adds a second cache layer between the data center that answers a request and the origin, in the region the topology of the cache setting selects. The first layer is the cache of that data center. On a miss in the first layer, the data center asks the Tiered Cache layer before the request goes to the origin, and each cache setting turns Tiered Cache on in its own `modules.cache.tiered_cache.enabled` field, on every plan. The setting must use _Override cache behavior_, or the API answers `21001`, and, with Application Accelerator on, a Max Age of at least 3 seconds; [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) covers the regions it runs in and the purge type that clears it. | +| Tiered Cache | A Feature of Cache that adds a second cache layer, in the region the topology of the cache setting selects, between the origin and the first layer, which is the cache of the data center that answers a request. On a miss in the first layer, the data center asks the Tiered Cache layer before the request goes to the origin, and [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) covers the regions it runs in and the purge type that clears it. Each cache setting turns Tiered Cache on in its own `modules.cache.tiered_cache.enabled` field, on every plan, and must use _Override cache behavior_, or the API answers `21001`, and, with Application Accelerator on, a Max Age of at least 3 seconds. | | TTL | Time to live: the number of seconds Azion's cache or the browser keeps a copy of an object. Under _Honor cache policies_, the `Cache-Control` and `Expires` headers the origin sends set it. When a [cache setting](/en/documentation/platform/applications/cache/cache-settings/) overrides them, its Max Age sets it: `modules.cache.max_age` for Azion's cache and `browser_cache.max_age` for the browser. | | URL purge | A [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#url-purge) type, `url` in the API, that clears the object behind each URL of a list. It is not recursive, and Azion converts each URL to its cache key without the variations, so an object that varies by cookie, device group, or image format needs a cache key or wildcard purge. Sent without a scheme, a URL clears the HTTP and the HTTPS copy alike. | | variable | A value of the request or the response, written `${name}`, that a criterion tests or a behavior argument inserts, such as `${uri}`, `${host}`, or `${device_group}`. Each variable is available in the Request Phase, the Response Phase, or both, as [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/#variables) lists. In an Application, `${request_uri}` requires Application Accelerator, and a rule that uses it while Application Accelerator is off is refused with `25047 Missing Required Modules`, while the same rule with `${uri}` is accepted. | diff --git a/apps/docs/src/content/docs/en/pages/build/applications/how-it-works.mdx b/apps/docs/src/content/docs/en/pages/build/applications/how-it-works.mdx index ebc901c3e5..3c27da6b03 100644 --- a/apps/docs/src/content/docs/en/pages/build/applications/how-it-works.mdx +++ b/apps/docs/src/content/docs/en/pages/build/applications/how-it-works.mdx @@ -9,13 +9,15 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Between a client and your content, a layer can read each request first, whether the request asks for a page, a file, or an API route. The layer then decides what happens to the request. It can run code that builds the response with no server behind it, stand in front of the server that holds your content, or do both. In front of that server, it can answer with a copy of a response that the server sent earlier, add or remove a header, or choose the server that receives the request. When a response comes back from that server, the same layer can change it before the client receives it. +Between a client and your content, a layer can read each request first, whether the request asks for a page, a file, or an API route. The layer then decides what happens to the request. It can run code that builds the response with no server behind it, stand in front of the server that holds your content, or do both. -On Azion, that layer is an Application. [Applications](/en/documentation/platform/applications/) is a Platform Resource that processes the requests received by your [Workloads](/en/documentation/platform/workloads/), on Azion's distributed infrastructure, from the data center nearest to your user. Each request reaches an Application through a Workload, which receives the request on one of its domains. The Workload's deployment sets the Application that processes the request. +In front of that server, it can answer with a copy of a response that the server sent earlier, add or remove a header, or choose the server that receives the request. When a response comes back from that server, the same layer can change it before the client receives it. -The Application acts on the request through its rules, which you write in [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/). Each rule belongs to one of two phases: Request Phase rules act on the request, and Response Phase rules act on the response that the user receives. To send the request to the origin, a Request Phase rule uses the _Set Connector_ behavior, which sets the [Connector](/en/documentation/platform/connectors/) that routes the request there. A rule can also run your code on the request: the _Run Function_ behavior invokes a [Function Instance](/en/documentation/platform/applications/functions-instances/) of one of your [Functions](/en/documentation/platform/functions/). +On Azion, that layer is an Application. [Applications](/en/documentation/platform/applications/) is a Platform Resource that processes the requests received by your [Workloads](/en/documentation/platform/workloads/), from the data center nearest to your user. Each request reaches an Application through a Workload, which receives the request on one of its domains. -Three Platform Resources nested in Applications act along the path from the Workload to the origin, each with its own switch in the Application. [Cache](/en/documentation/platform/applications/cache/) answers with a stored copy of an earlier response. [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) unlocks four capabilities for the cache and the rules of an Application. Among them, cache variation adds more of the request, such as a cookie or a query-string argument, to the cache key, the index under which Cache files each copy. [Image Processor](/en/documentation/platform/applications/image-processor/) builds a resized or converted image from an image on the origin. +The Application acts on the request through its rules, which you write in [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) and which run in two phases, first on the request and then on the response. A rule can set the [Connector](/en/documentation/platform/connectors/) that routes the request to your origin, or invoke a [Function Instance](/en/documentation/platform/applications/functions-instances/) of one of your [Functions](/en/documentation/platform/functions/). + +Three Platform Resources nested in Applications act along the path from the Workload to the origin, each with its own switch in the Application. [Cache](/en/documentation/platform/applications/cache/) answers with a stored copy of an earlier response, and [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) unlocks four capabilities for the cache and the rules of an Application. [Image Processor](/en/documentation/platform/applications/image-processor/) builds a resized or converted image from an image on the origin. This page explains the mechanisms, and two other pages hold the fields: Rules Engine for Applications lists every variable, operator, and behavior, and [Applications limits](/en/documentation/platform/applications/limits/) lists every bound. The sections follow a request along its path, then cover the two phases, how rules run, what a new Application has, and propagation. After them, one section each covers Cache, Application Accelerator, and Image Processor. [WebSocket Proxy](/en/documentation/platform/applications/websocket/) covers, on its own page, the WebSocket connections that an Application proxies to the origin, and [How Functions works](/en/documentation/platform/functions/how-it-works/) covers how a Function runs. @@ -23,9 +25,11 @@ This page explains the mechanisms, and two other pages hold the fields: Rules En ## The path a request travels -Creating an Application does not put it in the path of any request: a request reaches the Application only after a Workload's deployment sets that Application. The relation is stored on the deployment, not on the Application, and in Azion Console you set it in the **Application** field of the Workload's **Deployment Settings**. The deployment can also set a [Firewall](/en/documentation/platform/firewall/), and the request then crosses the Firewall before the Application receives it. The domains, protocols, and certificates are on the Workload too, so you configure delivery on the Workload, not on the Application. +Creating an Application puts it in the path of no request: a request reaches it only after a Workload's deployment sets that Application. The relation is stored on the deployment, not on the Application, and [Serve the Application from a Workload](/en/documentation/platform/applications/quickstart/#serve-the-application-from-a-workload) shows how to set it. The deployment can also set a [Firewall](/en/documentation/platform/firewall/), and the request then crosses the Firewall before the Application receives it. The domains, protocols, and certificates are on the Workload too, so you configure delivery on the Workload, not on the Application. + +The Application does not store an origin either: a request reaches an origin only when a Request Phase rule sends it there with the _Set Connector_ behavior. That behavior sets a Connector, and the Connector holds the address of the origin. An Application created with only `name` and `active` comes back with no field that points to a server, as [What a new Application has](/en/documentation/platform/applications/how-it-works/#what-a-new-application-has) shows. -The Application does not store an origin either: a request reaches an origin only when a Request Phase rule sends it there with the _Set Connector_ behavior. That behavior sets a Connector, and the Connector holds the address of the origin. The API shows this: an Application created with only `name` and `active` comes back with `modules`, `active`, and `debug`, and with no field that points to a server. Connectors replace the origins that earlier versions of Applications configured on the Application. In place of an origin, a Function can answer a request: a rule runs the Function with _Run Function_, and the Function builds the response with no Connector. +Connectors replace the origins that earlier versions of Applications configured on the Application. In place of an origin, a Function can answer a request: a rule runs the Function with _Run Function_, and the Function builds the response with no Connector. The diagram follows one request on the path to an origin, from the client to the response it receives. Solid arrows carry the request, and dotted arrows carry the response. Each label starts with the number of its step below. @@ -66,7 +70,9 @@ Because a rule chooses the origin of each request, one Application can route `/a ## Request and response phases -Each rule of an Application belongs to one phase, and the two phases run in a fixed order: the Request Phase before a response exists, then the Response Phase on the response that the Application delivers. You set the phase of a rule when you create it, and you cannot change it later. In the API, the endpoint that receives the rule sets its phase: `request_rules` or `response_rules`. To run the same logic in the other phase, add a second rule in that phase. +Each rule belongs to one of two phases, and the phases run in a fixed order: the Request Phase, then the Response Phase. The Request Phase runs before a response exists, and the Response Phase runs on the response that the Application delivers. + +You set the phase of a rule when you create it, and you cannot change it later. In the API, the endpoint that receives the rule sets its phase: `request_rules` or `response_rules`. To run the same logic in the other phase, add a second rule in that phase. The diagram follows a request on the path to an origin. Solid arrows carry the request, and dotted arrows carry the response. Each label starts with the number of its step below. @@ -96,7 +102,9 @@ flowchart TD Because the Request Phase runs first, the cache is decided before the response exists. A rule cannot apply a cache setting based on the status code that the origin returns, because `${status}` is readable only in the Response Phase, and _Set Cache Policy_ runs only in the Request Phase. -Some behaviors work in both phases, and the phase limits what they do. In a Response Phase rule, _Redirect To_ runs only when the origin returns `404`. So a redirect in that phase can send the user to another page when the origin has nothing at the path, and leave the requests for existing paths untouched. _Run Function_ also works in both phases, but the Response Phase accepts only Functions written in Lua. The Function Instance form in Azion Console states this limit: `Only Lua functions can be used in the Response phase.` [Phases](/en/documentation/platform/applications/rules-engine/#phases) lists the variables and behaviors that each phase accepts. +Some behaviors work in both phases, and the phase limits what they do. In a Response Phase rule, _Redirect To_ runs only when the origin returns `404`. So a redirect in that phase can send the user to another page when the origin has nothing at the path, and leave the requests for existing paths untouched. + +_Run Function_ also works in both phases, but the Response Phase accepts only Functions written in Lua. The Function Instance form in Azion Console states this limit: `Only Lua functions can be used in the Response phase.` [Phases](/en/documentation/platform/applications/rules-engine/#phases) lists the variables and behaviors that each phase accepts. --- @@ -138,7 +146,7 @@ Some behaviors cannot share a rule, and the API and Azion Console both refuse th ### Behaviors that repeat -When several rules match a request and carry the same Set behavior, such as _Set Connector_, the behavior does not accumulate: only the one in the last matching rule runs. For example, a first rule sets a Connector for every path, and a second rule sets another Connector for `/api/`. A request to `/api/` matches both rules, so the Connector of the second rule routes it. +When several matching rules carry the same Set behavior, such as _Set Connector_, only the one in the last matching rule runs. For example, a first rule sets a Connector for every path, and a second rule sets another Connector for `/api/`. A request to `/api/` matches both rules, so the Connector of the second rule routes it. _Add Request Header_ does not repeat a header either: when two matching rules add a header with the same name, the origin receives it once, with the value of the last of those rules. @@ -148,7 +156,9 @@ So the order of the rules shapes the result as much as their content does. A bro Some behaviors stop the processing of a request, and nothing after them runs: no later behavior in their rule, and no later rule. _Deny (403 Forbidden)_ answers with a `403 Forbidden` page, _Deliver_ delivers the content to the user, and _Redirect To_ sends the user to another URL with a `301` or `302` status. _Finish Request Phase_ ends the Request Phase at the point where it runs, so the rest of its rule and every later rule of that phase are skipped. -An ending behavior saves work, and it can also hide a rule. Early in the list, it settles the request before later rules spend time on it. Placed before a rule that you still need, it stops that rule for every request that the earlier rule matches. With Debug Rules on, [Real-Time Events](/en/documentation/platform/real-time-events/) and [Data Stream](/en/documentation/platform/data-stream/) show which rules each request ran. Debug Rules is the `debug` field of the Application in the API, and [Main Settings](/en/documentation/platform/applications/main-settings/#debug-rules) shows where to turn it on in Azion Console. +An ending behavior saves work, and it can also hide a rule. Early in the list, it settles the request before later rules spend time on it. Placed before a rule that you still need, it stops that rule for every request that the earlier rule matches. + +With Debug Rules on, [Real-Time Events](/en/documentation/platform/real-time-events/) and [Data Stream](/en/documentation/platform/data-stream/) show which rules each request ran. Debug Rules is the `debug` field of the Application in the API, and [Main Settings](/en/documentation/platform/applications/main-settings/#debug-rules) shows where to turn it on in Azion Console. --- @@ -169,9 +179,9 @@ A new Application has two switches on, Cache and Functions, and no rules. When y } ``` -Its list of request rules is empty, with `count` at `0`. The four keys of `modules` are the four switches of an Application, and [Main Settings](/en/documentation/platform/applications/main-settings/#platform-resources) shows each one in Azion Console and the API. Cache cannot be turned off: the API refuses `false` in `modules.cache.enabled` with `31001`, and in Azion Console the **Cache** switch is locked on, with the note `Automatically enabled in all accounts.` [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) is not one of these switches: it is a Feature of Cache, and each cache setting turns it on in its `modules.cache.tiered_cache.enabled` field. +Its list of request rules is empty, with `count` at `0`. The four keys of `modules` are the four switches of an Application, and [Main Settings](/en/documentation/platform/applications/main-settings/#platform-resources) shows each one in Azion Console and the API. Cache cannot be turned off: the API refuses `false` in `modules.cache.enabled` with `31001`. [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) is not one of these switches: it is a Feature of Cache, and each cache setting turns it on in its `modules.cache.tiered_cache.enabled` field. -Cache is on, but it stores copies only after a rule applies a cache setting, and a new Application has no cache settings and no rules. Cache starts storing copies once you create a cache setting and a _Set Cache Policy_ rule that applies it. +Cache is on, but a new Application has no cache settings and no rules. Cache starts storing copies only once you create a cache setting and a _Set Cache Policy_ rule that applies it. While a switch is off, the rule options that depend on it are unavailable. The **Rules Engine** form in Azion Console labels each of those options with _- Required Application Accelerator_, _- Required Image Processor_, or _- Required Function_, and the API refuses a rule that uses one. For example, on an Application with Application Accelerator off, a request rule with a criterion on `${request_uri}` returns `400` with this body: @@ -214,7 +224,7 @@ A cache stores a copy of an origin response in the data center that fetched it. In an Application, Cache stores those copies, and it is on in every Application you create. A cache setting belongs to one Application and holds the TTLs and the inputs that make two requests different. A cache setting acts only through a Request Phase rule, which applies that cache setting with _Set Cache Policy_ to the requests that the rule matches. _Bypass Cache_ does the opposite and sends the request past the cache. -[Cache settings](/en/documentation/platform/applications/cache/cache-settings/) lists every field and its default, and [Cache keys](/en/documentation/platform/applications/cache/cache-keys/) gives the full key format. To vary the cache by query string, cookie, device group, or method, you need [Application Accelerator](/en/documentation/platform/applications/application-accelerator/). [Cache quickstart](/en/documentation/platform/applications/cache/quickstart/) creates a first cache setting and the rule that applies it. +To vary the cache by query string, cookie, device group, or method, a cache setting needs Application Accelerator on in the Application. The [Cache overview](/en/documentation/platform/applications/cache/#request-path) shows where Cache acts on a request, and [Expiration and freshness](/en/documentation/platform/applications/cache/expiration-and-freshness/) explains how long a copy lives and what ends it. @@ -224,7 +234,7 @@ The [Cache overview](/en/documentation/platform/applications/cache/#request-path A cache key built from the URL alone assumes that each URL has one correct response. Dynamic content breaks that assumption: under a single URL, a signed-in visitor sees their own cart, a listing reorders when a filter changes, and the layout differs on a phone. With a key built from the URL alone, the cache either serves one visitor's response to another, or it cannot cache the path at all. -In an Application, Application Accelerator unlocks cache variation, which removes that assumption, and three more capabilities for dynamic content. It is off in a new Application, and each Application turns it on separately, in its `modules.application_accelerator.enabled` field in the API. Each cache setting then holds its own variations, in its own `modules.application_accelerator` object. If you have written a `Vary` header or a cache-key rule, the model is the same: you list the inputs that make two requests different. [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/) lists each field, its type, and its default, and [Applications limits](/en/documentation/platform/applications/limits/#application-accelerator) gives the TTL bounds. To turn Application Accelerator on and add a first variation to a cache setting, refer to [Application Accelerator quickstart](/en/documentation/platform/applications/application-accelerator/quickstart/). +In an Application, Application Accelerator unlocks cache variation, which removes that assumption, and three more capabilities for dynamic content. It is off in a new Application, and each Application turns it on separately, in its `modules.application_accelerator.enabled` field in the API. Each cache setting then holds its own variations, in its own `modules.application_accelerator` object. If you have written a `Vary` header or a cache-key rule, the model is the same: you list the inputs that make two requests different. The [Application Accelerator overview](/en/documentation/platform/applications/application-accelerator/#request-path) shows how a variation changes the cache key, and [Cache variation](/en/documentation/platform/applications/application-accelerator/cache-variation/) explains what turning it on unlocks and what each variation costs. @@ -234,9 +244,11 @@ The [Application Accelerator overview](/en/documentation/platform/applications/a A page often needs the same image in several sizes, crops, and formats, one for each layout and browser. Preparing every variant in advance means one stored file per variant, and a rebuild of all of them whenever the original changes. Transforming the image at request time avoids both: the URL describes the variant, and the platform builds it from one original when a request asks for it. -In an Application, Image Processor builds those variants. The request URL describes the variant in its `ims` query string, and Image Processor applies that description to the source image on the origin. Even with no `ims` query string, Image Processor can convert the image to a format the browser accepts. The result, the derived image, is what the client receives. Image Processor reads the source image without changing it, and it returns the derived image without saving it as an asset of the account. So one file on the origin serves every size, crop, quality, and format that a page requests. +In an Application, Image Processor builds those variants. The request URL describes the variant in the `ims` parameter, and Image Processor applies that description to the source image on the origin. Even with no `ims` parameter, Image Processor can convert the image to a format the browser accepts. The result, the derived image, is what the client receives. + +Image Processor reads the source image without changing it, and it returns the derived image without saving it as an asset of the account. So one file on the origin serves every size, crop, quality, and format that a page requests. -Image Processor is off in a new Application, and each Application turns it on separately, in its `modules.image_processor.enabled` field in the API. Even when it is on, Image Processor acts only on the requests that a Request Phase rule with _Optimize Images_ matches. [Image Processor URL parameters](/en/documentation/platform/applications/image-processor/url-parameters/) lists the operations that `ims` accepts, and [Image Processor settings](/en/documentation/platform/applications/image-processor/settings/) covers the headers and behaviors. To turn Image Processor on and request a first derived image, follow [Image Processor quickstart](/en/documentation/platform/applications/image-processor/quickstart/). +Image Processor is off in a new Application, and each Application turns it on separately, in its `modules.image_processor.enabled` field in the API. Even when it is on, Image Processor acts only on the requests that a Request Phase rule with _Optimize Images_ matches. The [Image Processor overview](/en/documentation/platform/applications/image-processor/#request-path) shows where Image Processor acts on a request, and [Image delivery](/en/documentation/platform/applications/image-processor/image-delivery/) explains how the delivered format is chosen and where Image Processor stops. diff --git a/apps/docs/src/content/docs/en/pages/build/applications/limits.mdx b/apps/docs/src/content/docs/en/pages/build/applications/limits.mdx index a2dc6d345f..4fa3f1ed37 100644 --- a/apps/docs/src/content/docs/en/pages/build/applications/limits.mdx +++ b/apps/docs/src/content/docs/en/pages/build/applications/limits.mdx @@ -10,11 +10,25 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -An [Application](/en/documentation/platform/applications/) processes the requests received by your [Workloads](/en/documentation/platform/workloads/): it runs its request and response [rules](/en/documentation/platform/applications/rules-engine/) on each request. With [WebSocket Proxy](/en/documentation/platform/applications/websocket/) turned on for the account, it can also proxy WebSocket connections to the origin. An Application receives the requests of a Workload once that Workload's deployment sets that Application. +An [Application](/en/documentation/platform/applications/) processes the requests received by your [Workloads](/en/documentation/platform/workloads/): it runs its request and response [rules](/en/documentation/platform/applications/rules-engine/) on each request. Each Platform Resource turned on in the Application adds bounds of its own. [Cache](/en/documentation/platform/applications/cache/) bounds [cache settings](/en/documentation/platform/applications/cache/cache-settings/) and the objects it stores, and [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/) bounds purge requests. [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) moves the floor of the cache time to live (TTL), and [Image Processor](/en/documentation/platform/applications/image-processor/) bounds the size, width, and height of one image. This page states each bound and the answer a call receives where the API refuses it. -A service plan also includes an amount of usage before a rate applies. That amount is a billing quantity: passing it changes what the account is charged rather than what the call returns. [Azion pricing](https://www.azion.com/en/pricing/) lists the plans and the usage each one includes. For the rates, refer to [Pricing](/en/documentation/fundamentals/pricing/#applications). +A Platform Resource that you turn on can add costs that depend on usage, and a service plan includes an amount of usage before a rate applies. That amount is a billing quantity: passing it changes what the account is charged rather than what the call returns. [Azion pricing](https://www.azion.com/en/pricing/) lists the plans and the usage each one includes. For the rates, refer to [Pricing](/en/documentation/fundamentals/pricing/#applications). + +--- + +## Scope + +These boundaries hold for every Application, whichever Platform Resources are turned on in it. The boundaries of each nested Platform Resource open its own section of this page. + +- **Phases**: every rule belongs to one of two phases, which you choose when you create the rule and cannot change later. The Request Phase acts on the request before a response exists, and the Response Phase acts on the response that the user receives. Only Request Phase rules can choose the origin and the cache setting. [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/#phases) lists the variables and behaviors of each phase and the Platform Resource that each one needs. +- **Origins**: an Application reaches each origin through a [Connector](/en/documentation/platform/connectors/) that a rule sets, so two rules with two Connectors can route `/api/` to one server and every other path to another. The origin behind a Connector can be a web server in your infrastructure, a cloud service, or an [Object Storage](/en/documentation/platform/object-storage/) bucket, as [Use a bucket as an application origin](/en/documentation/guides/application-development/data/use-bucket-as-origin/) shows. With [Load Balancer](/en/documentation/platform/connectors/load-balancer/) enabled, one Connector of the `http` type can spread traffic across several origins. Connectors replace the origins that earlier versions of Applications configured on the Application. +- **Functions**: a [Function Instance](/en/documentation/platform/applications/functions-instances/) belongs to one Application, and it runs only when a rule with _Run Function_ invokes it. Functions starts on in a new Application, in its `modules.functions.enabled` field in the API. Only Functions written in Lua run in the Response Phase, as the Function Instance form in Azion Console states: `Only Lua functions can be used in the Response phase.` For the steps to add your first Function, refer to [Instantiate a function on an application](/en/documentation/guides/application-development/getting-started/instantiate-functions/). +- **Devices**: a [device group](/en/documentation/platform/applications/device-groups/) is a name and a regular expression that the Application compares with the `User-Agent` header of each request. Both uses of a group need Application Accelerator on: a rule tests the group through `${device_group}`, and a cache setting can keep one copy per group. [Applications best practices](/en/documentation/platform/applications/best-practices/#match-a-device-group-on-the-words-that-only-that-device-sends) shows how to write an expression that matches only the devices you mean. +- **WebSocket**: Azion turns [WebSocket Proxy](/en/documentation/platform/applications/websocket/) on for an account only on request, and [Support guidelines](/en/documentation/support/) explains how to ask. A WebSocket connection opens with the `Upgrade: websocket` and `Connection: upgrade` headers. Azion recycles the keepalive connections on its servers approximately every 15 minutes, so an active connection that needs more time can be terminated. When a WebSocket connection closes this way, your client code has to detect the closed connection and open it again. +- **Large files**: the same keepalive cycle can end a long transfer, and either of two options lets each transfer finish before the connection is recycled. With `modules.cache.large_file_cache.enabled` set to `true` in a cache setting, Cache stores the file in fragments, as [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#cache) shows. The other option, compression, shrinks the file, as [Compress application responses with gzip](/en/documentation/guides/application-performance/delivery-optimization/gzip-compression/) shows. +- **Workloads**: a Workload holds the domains, protocols, and certificates that serve the Application, so you configure delivery on the Workload, not on the Application. _Redirect HTTP to HTTPS_ works only when the Workload has HTTPS. When the Connector receives a 4xx or 5xx response from your origin, the client sees the error page of the custom page set that the Workload's deployment sets, in [Custom Pages](/en/documentation/platform/custom-pages/). To request an Application on your own domain from one device before you change its DNS records, refer to [Test an application through the hosts file](/en/documentation/guides/application-development/getting-started/stage-applications-through-hosts-file/). --- @@ -40,22 +54,26 @@ Three further bounds apply to names: an Application's name takes 1 to 100 charac The 200 rules are one total that the request phase and the response phase share. For example, an Application can carry 150 request rules and 50 response rules, but not 200 of each. -Azion recycles the keepalive connections on its servers approximately every 15 minutes. That cycle bounds how long a connection between a user and an Application stays open. An active connection that needs more time can be terminated. When a WebSocket connection closes this way, your client code has to detect the closed connection and open it again. - -For a large file, either of two options lets each transfer finish before the connection is recycled. With `modules.cache.large_file_cache.enabled` set to `true` in a cache setting, Cache stores the file in fragments of 1,024 kB. The other option, compression, shrinks the file. - -To store a large file in fragments, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#cache). To compress it, refer to [Compress application responses with gzip](/en/documentation/guides/application-performance/delivery-optimization/gzip-compression/). - --- ## Cache -Cache bounds a cache setting and an object it stores, and Real-Time Purge bounds a purge request. Past a bound that the API checks, the call returns HTTP `400` with an error code and a title. [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) changes two bounds of a cache setting: the lowest TTL it takes and the cache behavior it allows. - -The API validates the TTL bounds on every cache setting. +Cache bounds a cache setting and an object it stores, and Real-Time Purge bounds a purge request. The API validates the TTL bounds on every cache setting, and past a bound that it checks, the call returns HTTP `400` with an error code and a title. [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) changes two bounds of a cache setting: the lowest TTL it takes and the cache behavior it allows. For the rates of Cache, refer to [Pricing](/en/documentation/fundamentals/pricing/#cache). To query the data that Tiered Cache transferred, refer to [Query usage data from Tiered Cache](/en/documentation/guides/platform/observability/query-tiered-cache-usage-data-with-graphql/). +### Scope + +These boundaries hold for Cache in every Application, from any interface. + +- **Always on**: Cache is on in every Application, and the API refuses `false` in its `modules.cache.enabled` field with error `31001`. In Azion Console, the **Cache** switch of **Main Settings** is locked on, with the note `Automatically enabled in all accounts.` A new Application has no cache settings and no rules, so Cache stores copies only once a rule with _Set Cache Policy_ applies a cache setting. +- **Expired copies**: with stale cache turned on in `modules.cache.stale_cache.enabled` of a cache setting, Azion may serve an expired copy when it cannot confirm the copy with the origin, and the response then reports `STALE`. A setting created through Azion API or Azion CLI has stale cache off, while Azion Console turns it on for a new setting, as [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#cache) shows. For when an old page is better than an error, refer to [Applications best practices](/en/documentation/platform/applications/best-practices/#cache). +- **Large files**: Large File Optimization is off in a new cache setting, and a cache setting turns it on in `modules.cache.large_file_cache.enabled`. Each fragment of a large file is fetched when a user reaches it and stored under a key of its own, so a purge of the file has to name every fragment or use a wildcard. +- **Tiered Cache**: [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) adds a second cache layer between the data center that answers a request and the origin, and it requires the `override` behavior and a minimum TTL. Each cache setting turns it on in its `modules.cache.tiered_cache.enabled` field, and every plan includes it. A _Bypass Cache_ rule acts on Azion's cache only, so the Tiered Cache layer keeps caching objects for the Max Age of the cache setting. +- **Keys and variation**: Azion builds the default [cache key](/en/documentation/platform/applications/cache/cache-keys/) from the scheme, the host, and the path, so one path is one stored object, and the query string stays out of the key. [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) lets a cache setting keep a separate copy for each value of a query-string argument, a cookie, the device group, or the method. [Image Processor](/en/documentation/platform/applications/image-processor/) adds the format of a converted image to the key. +- **Purge**: [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/) queues a purge after you confirm it, because the result takes time to propagate, and the purge history lists the purge once it completes. A copy that varies by cookie, device group, or image format survives a URL purge, and a cache key or wildcard purge reaches it. +- **Code**: Cache cannot run code, so code that reads and writes cached entries runs in a [Function](/en/documentation/platform/functions/) and calls [Cache API](/en/documentation/devtools/runtime/api-reference/cache/). + ### Cache settings Each bound in this table applies to one cache setting, from any interface that writes it. The Scope column names the API field and, where one exists, the Console label. The Past the limit column carries the code and the title of the `400` answer. The error titles keep earlier names: `Edge Cache` stands for Cache, and `Module` stands for a Platform Resource turned on in the Application. @@ -113,6 +131,18 @@ Application Accelerator changes one bound of a cache setting: the shortest time For the rates of Application Accelerator, refer to [Pricing](/en/documentation/fundamentals/pricing/#application-accelerator). +### Scope + +These boundaries hold for Application Accelerator in every Application, from any interface. + +- **One Application at a time**: Application Accelerator is off in a new Application, and it belongs to the Application, so one Application can have it on while another has it off. Turning it on leaves traffic as it was: the variation controls of a cache setting start at `ignore`, and a cache setting reaches a request only through a [Set Cache Policy](/en/documentation/platform/applications/rules-engine/#set-cache-policy) rule. [Main Settings](/en/documentation/platform/applications/main-settings/#platform-resources) shows where to turn it on in Azion Console and the API. +- **All or none**: an Application takes every capability that Application Accelerator unlocks, or none of them. They are cache variation, the caching of `POST` and `OPTIONS` responses, a lower floor for the Max Age, the `${request_uri}` and `${device_group}` variables, and the Rules Engine behaviors that [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/) lists. +- **Methods**: an Application passes `POST`, `PUT`, `PATCH`, `DELETE`, and `OPTIONS` requests to the origin with or without Application Accelerator. Of those methods, Application Accelerator makes only the `POST` and `OPTIONS` responses cacheable. A `POST` reports `-` in `x-cache` until the `cache_vary_by_method` field of the cache setting carries `post`. +- **Variation size**: each distinct value of a varied input is a separate cached object. A cookie unique to each visitor gives every visitor a copy, so the number of objects grows with the audience instead of with the content. An allowlist and sorting, the `sort_enabled` field, bound that number, as [Cache variation](/en/documentation/platform/applications/application-accelerator/cache-variation/#the-cost-of-a-variation) explains. For the practices, refer to [Applications best practices](/en/documentation/platform/applications/best-practices/#application-accelerator). +- **Purges**: copies that vary by cookie or device group survive a URL purge, and a cache key purge or a wildcard purge that ends the key with `@@*` reaches them. Copies that vary by query string are the exception: a URL purge reaches them when it sends the arguments in the order they were presented, or in alphabetical order with `sort_enabled` on. For the purge types, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#purge-content-that-varies). +- **Bypass Cache and a TTL of 0**: [Bypass Cache](/en/documentation/platform/applications/rules-engine/#bypass-cache) sends each request that its rule matches to the origin and keeps the response out of Azion's cache, but not out of the Tiered Cache layer of a cache setting that turns Tiered Cache on. A Max Age of 0 seconds keeps the request on the cache path, and every request still reaches the origin. [Bypass Cache and a TTL of 0](/en/documentation/platform/applications/application-accelerator/cache-variation/#bypass-cache-and-a-ttl-of-0) compares how the two handle a request. +- **Image Processor**: to vary the cache on the `ims` string of [Image Processor](/en/documentation/platform/applications/image-processor/), add `ims` to the query-string allowlist of the cache setting that serves images. + ### Default limits Each row names a cache TTL bound and the condition that puts it in force. @@ -126,9 +156,9 @@ Each row names a cache TTL bound and the condition that puts it in force. A Max Age lower than the minimum in force returns HTTP `400`. The error is `21021` while Application Accelerator is off, and `21020` while Application Accelerator and Tiered Cache are both on. A value higher than the maximum returns error `10068`. For the error titles, refer to [Cache settings](#cache-settings). -For how a Max Age of 0 seconds and the _Bypass Cache_ behavior each handle a request, refer to [Bypass Cache and a TTL of 0](/en/documentation/platform/applications/application-accelerator/cache-variation/#bypass-cache-and-a-ttl-of-0). +A request that Application Accelerator varies is still bounded by the Platform Resources that store the object and run code on it. Cache bounds the object itself: the size of one cached object, and the size of each fragment of a large file. For those values, refer to [Cached objects](#cached-objects). -A request that Application Accelerator varies is still bounded by the Platform Resources that store the object and run code on it. Cache bounds the object itself: the size of one cached object, and the size of each fragment of a large file. For those values, refer to [Cached objects](#cached-objects). A [Function](/en/documentation/platform/functions/) that the Application runs carries its own limits on its code and on each invocation. For those values, refer to [Functions limits](/en/documentation/platform/functions/limits/). +A [Function](/en/documentation/platform/functions/) that the Application runs carries its own limits on its code and on each invocation. For those values, refer to [Functions limits](/en/documentation/platform/functions/limits/). --- @@ -138,9 +168,18 @@ Image Processor bounds a single image with three default limits: its size, its w For the rates of the Images metric, refer to [Pricing](/en/documentation/fundamentals/pricing/#image-processor). To query the number of images the account has processed, refer to [Query usage data from Image Processor](/en/documentation/guides/platform/observability/query-image-processor-usage-data-with-graphql/). +### Scope + +These boundaries hold for Image Processor in every Application, from any interface. + +- **One Application at a time**: Image Processor is off in a new Application, and each Application turns it on separately, in its `modules.image_processor.enabled` field in the API. Even when it is on, Image Processor processes only the requests that a rule with _Optimize Images_ matches. [Main Settings](/en/documentation/platform/applications/main-settings/#platform-resources) shows where to turn it on in Azion Console and the API. +- **Parameters it cannot parse**: an `ims` value that Image Processor cannot parse returns the source image untransformed. For the syntax that each operation accepts, refer to [URL parameters](/en/documentation/platform/applications/image-processor/url-parameters/). +- **Storage**: Image Processor returns each derived image without saving it as an asset of the account, and you cannot upload images to Image Processor. The cache holds the derived images, and the source image stays where it already lives. A workflow that needs to keep a transformed file saves the response itself. +- **Code**: [WASM Image Processor](/en/documentation/devtools/azion-lib/wasm-image-processor/) is a WebAssembly library that processes images inside a [Function](/en/documentation/platform/functions/). It runs in the code of that Function, separately from Image Processor and its settings, as [Where Image Processor stops](/en/documentation/platform/applications/image-processor/image-delivery/#where-image-processor-stops) explains. + ### Default limits -Image Processor applies three default limits to an image: a maximum size of 150 MB, a maximum width of 3,840 pixels, and a maximum height of 2,160 pixels. +An image takes at most 150 MB, 3,840 pixels of width, and 2,160 pixels of height. Each `ims` parameter also accepts a range of values of its own. For the range of each parameter, refer to [URL parameters](/en/documentation/platform/applications/image-processor/url-parameters/). diff --git a/apps/docs/src/content/docs/en/pages/build/applications/troubleshooting.mdx b/apps/docs/src/content/docs/en/pages/build/applications/troubleshooting.mdx index 99def27c44..000eaaa78b 100644 --- a/apps/docs/src/content/docs/en/pages/build/applications/troubleshooting.mdx +++ b/apps/docs/src/content/docs/en/pages/build/applications/troubleshooting.mdx @@ -43,7 +43,7 @@ A client then receives your page for an origin error, or the expired copy of a c ## A rule does not act on the requests you expect -A rule is saved, and requests you meant it to catch keep the previous behavior. +A rule is saved, and requests you meant it to catch keep the previous response. A rule acts only on the requests its criteria match, and only after the change propagates. Check three causes: @@ -51,7 +51,7 @@ A rule acts only on the requests its criteria match, and only after the change p - **The criteria do not match the request**: [Criteria](/en/documentation/platform/applications/rules-engine/#criteria) lists each variable, operator, and conditional. - **An earlier rule ended the processing**: a behavior such as _Deny (403 Forbidden)_ stops the behaviors and rules after it, as [How rules run](/en/documentation/platform/applications/how-it-works/#how-rules-run) explains. -To tell the three apart, check which rules ran on the request. Debug Rules logs the Rules Engine rules that run on each request, and it is off in a new Application. +To tell the three apart, check which rules ran on the request. Debug Rules, the setting of an Application that logs the Rules Engine rules each request runs, is off in a new Application. - **Turn on Debug Rules**: in Azion Console, on the **Main Settings** tab of the Application, turn on **Debug Rules** and select **Save**. Through the API, set the Application's `debug` field to `true`. - **Read the rules that ran**: the `$traceback` field of each log lists them, as [Debug Rules](/en/documentation/platform/applications/main-settings/#debug-rules) describes. A rule missing from the log of a request did not run on it: rework its criteria, or move it ahead of the rule that ended the processing. @@ -77,9 +77,9 @@ The metrics and logs then show which requests, paths, or periods carry the probl ## A rule is refused with Missing Required Modules -Saving a request rule that reads `${request_uri}` fails with `400` and code `25047` while Application Accelerator is off, as [Errors](/en/documentation/platform/applications/rules-engine/#errors) shows in full. +Saving a request rule that reads `${request_uri}` fails with `400`, code `25047`, and `Missing Required Modules` while Application Accelerator is off, as [Errors](/en/documentation/platform/applications/rules-engine/#errors) shows in full. -Some variables and behaviors belong to a Platform Resource, and the API refuses a rule that uses one while that Platform Resource is off: `meta.missing_required_modules` names it. +Some variables and behaviors require a Platform Resource turned on in the Application, and the API refuses a rule that uses one while that Platform Resource is off: `meta.missing_required_modules` names it. - **Match on `${uri}` instead**: it needs no Platform Resource, so the same rule returns `202`, as [Variables](/en/documentation/platform/applications/rules-engine/#variables) lists for every variable. - **Turn on the Platform Resource the error names**: in Azion Console, its switch is in the **Modules** section of the Application's **Main Settings** tab, and **Save** applies it. [Main Settings](/en/documentation/platform/applications/main-settings/#platform-resources) gives its Azion CLI flag and API key. @@ -159,7 +159,7 @@ Responses to the cached method then carry a status, and a key that starts with t Requests that a _Bypass Cache_ rule matches keep getting a stored copy, and the origin does not see them. -_Bypass Cache_ keeps Azion's cache from storing the response, but the [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/#bypass-cache) layer is outside its reach. While a cache setting keeps Tiered Cache on, that layer goes on storing objects for the Max Age of the cache setting, and it answers before the origin does. +_Bypass Cache_ sends the requests its rule matches to the origin and keeps the response out of Azion's cache, but the [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/#bypass-cache) layer is outside its reach. While a cache setting keeps Tiered Cache on, that layer goes on storing objects for the Max Age of the cache setting, and it answers before the origin does. - **Turn off Tiered Cache**: in Azion Console, in the **Cache** section of the cache setting that serves the path. Through the API, set `modules.cache.tiered_cache.enabled` to `false` in that setting. - **Purge both layers, the tiered one first**: purge Tiered Cache by cache key, then Cache, so the first layer cannot refill from a stale copy, as [Purge cached content](/en/documentation/guides/application-performance/cache-and-purge/purge-cached-content/) shows. @@ -178,16 +178,16 @@ A stored copy stays in cache until its TTL ends or a purge removes it, even afte On its next request, the purged URL reports `x-cache: MISS`, and the response carries the new version. -### A purge did not expire a variation of the object +### A purge did not expire a copy of the object The purge was accepted, yet some visitors, or some query strings, keep getting the old content. -A URL purge maps each URL to one cache key without variation, so copies that vary by cookie, device group, or image format survive it, however often you repeat it. It reaches a query string variation only when the URL lists the arguments in the order the key stores them, alphabetical when the variation has `sort_enabled` set to `true`. +A URL purge maps each URL to one cache key without variation, so copies that vary by cookie, device group, or image format survive it, however often you repeat it. It reaches a copy that varies by query string only when the URL lists the arguments in the order the key stores them, alphabetical when the query string variation has `sort_enabled` set to `true`. -- **Purge by cache key**: list every variation of the object, at most 50 keys in one request, each copied from the `x-cache-key` header of its response. -- **Purge by wildcard**: end the expression with `@@*` for the variations that add the `@@` separator, such as cookie and device group, or with `?*` for query string variations. +- **Purge by cache key**: list the key of each copy of the object, at most 50 keys in one request, each copied from the `x-cache-key` header of its response. +- **Purge by wildcard**: end the expression with `@@*` for the copies whose variation adds the `@@` separator, such as cookie and device group, or with `?*` for copies that vary by query string. -On its next request, each purged variation reports `x-cache: MISS`, as [Purge content that varies](/en/documentation/platform/applications/cache/real-time-purge/#purge-content-that-varies) shows for each kind of variation. +On its next request, each purged copy reports `x-cache: MISS`, as [Purge content that varies](/en/documentation/platform/applications/cache/real-time-purge/#purge-content-that-varies) shows for each kind of variation. ### A Max Age below 60 seconds is refused with error 21021 @@ -202,7 +202,7 @@ The cache setting is then accepted, within the bounds that [Applications limits] ### Tiered Cache cannot be turned on and the API returns 21001 or 21020 -A cache setting that sends `tiered_cache.enabled` as `true` is refused with `400`: code `21001` answers the `honor` cache behavior, and code `21020` a Max Age below 3 seconds, as [Errors](/en/documentation/platform/applications/cache/cache-settings/#errors) details for each. +A cache setting that sends `tiered_cache.enabled` as `true` is refused with `400` and code `21001` or `21020`. Code `21001` answers the `honor` cache behavior, and code `21020` answers a Max Age below 3 seconds, as [Errors](/en/documentation/platform/applications/cache/cache-settings/#errors) details for each. Tiered Cache needs the _Override cache behavior_ in Azion Console, `override` in the API, and a Max Age of at least 3 seconds. With Application Accelerator off, the 60-second floor of error `21021` applies first, so 3 to 59 seconds is still refused. @@ -211,12 +211,24 @@ Tiered Cache needs the _Override cache behavior_ in Azion Console, `override` in ```bash cat > cache-setting.json <<'EOF' -{"name":"tiered-from-file","modules":{"cache":{"behavior":"override","max_age":600,"tiered_cache":{"enabled":true,"topology":"nearest-region"}}}} +{ + "name": "tiered-from-file", + "modules": { + "cache": { + "behavior": "override", + "max_age": 600, + "tiered_cache": { + "enabled": true, + "topology": "nearest-region" + } + } + } +} EOF azion create cache-setting --application-id --file cache-setting.json ``` -The CLI prints `Created Cache Settings configuration with ID `, and the setting reads back with `enabled` set to `true` under `tiered_cache`. For the topologies, refer to [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/). +Replace `` with the ID of your Application. The CLI prints `Created Cache Settings configuration with ID `, and the setting reads back with `enabled` set to `true` under `tiered_cache`. For the topologies, refer to [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/). ### A cache setting cannot be deleted and the API returns 21014 @@ -231,7 +243,7 @@ The _Set Cache Policy_ behavior of some rule still applies the setting, and a se azion delete cache-setting --application-id --cache-setting-id --format json ``` -With no rule applying the setting, the CLI prints `{"message": "Caches settings configuration was successfully deleted"}`, and the setting leaves the **Cache Settings** list in Azion Console. +Replace `` with the ID of your Application and `` with the ID of the setting. With no rule applying the setting, the CLI prints `{"message": "Caches settings configuration was successfully deleted"}`, and the setting leaves the **Cache Settings** list in Azion Console. ### A purge request is rejected with 30001, 30003, or 30005 @@ -249,7 +261,7 @@ Azion CLI reports `30001` with the detail of the API, as this URL purge on the T azion purge --urls "https:///" --layer tiered_cache ``` -The command prints `Error: ["Invalid purge layer for purge type \"url\"."]`. A purge by cache key on the same layer prints `Purge carried out successfully`, and accepted purges return `201` with `state` set to `executed`, as [Request body](/en/documentation/platform/applications/cache/real-time-purge/#request-body) shows. +Here `` and `` stand for a domain of your account and a path on it. The command prints `Error: ["Invalid purge layer for purge type \"url\"."]`. A purge by cache key on the same layer prints `Purge carried out successfully`, and accepted purges return `201` with `state` set to `executed`, as [Request body](/en/documentation/platform/applications/cache/real-time-purge/#request-body) shows. ### Azion CLI prints an empty error object @@ -266,38 +278,38 @@ Plain output then shows why the API refused the request, and the corrected reque ## Application Accelerator -Application Accelerator unlocks four capabilities for the cache and the rules of an Application: cache variation, the caching of `POST` and `OPTIONS` responses, a Max Age below 60 seconds, and further Rules Engine behaviors and variables. It is off in a new Application. For how a variation changes the key, refer to the [Application Accelerator overview](/en/documentation/platform/applications/application-accelerator/#request-path). +Application Accelerator unlocks four capabilities for the cache and the rules of an Application. They are cache variation, the caching of `POST` and `OPTIONS` responses, a Max Age below 60 seconds, and further Rules Engine behaviors and variables. It is off in a new Application. For how a variation changes the key, refer to the [Application Accelerator overview](/en/documentation/platform/applications/application-accelerator/#request-path). ### A POST request reports no cache status -A `POST` reports `-` in `x-cache` until Application Accelerator is on and the cache setting caches the method: _POST_ in **Cache vary by Method** in Azion Console, or `post` in `cache_vary_by_method` in the API. [HTTP methods](/en/documentation/platform/applications/application-accelerator/settings/#http-methods) shows the field for each interface. For the fix, refer to [The x-cache header reports a dash on every response for a path](/en/documentation/platform/applications/troubleshooting/#the-x-cache-header-reports-a-dash-on-every-response-for-a-path). +A `POST` reports `-` in `x-cache` until Application Accelerator is on and the cache setting caches the method. The setting takes _POST_ in **Cache vary by Method** in Azion Console, or `post` in `cache_vary_by_method` in the API. [HTTP methods](/en/documentation/platform/applications/application-accelerator/settings/#http-methods) shows the field for each interface. For the fix, refer to [The x-cache header reports a dash on every response for a path](/en/documentation/platform/applications/troubleshooting/#the-x-cache-header-reports-a-dash-on-every-response-for-a-path). -### Cookie and device group variations survive a purge +### Copies that vary by cookie or device group survive a purge -These variations come from the `modules.application_accelerator` object of the cache setting, the **Application Accelerator** section in Azion Console. Each one is an object under its own key, out of reach of a URL purge. For the purge by cache key or by the `@@*` wildcard that does, refer to [A purge did not expire a variation of the object](/en/documentation/platform/applications/troubleshooting/#a-purge-did-not-expire-a-variation-of-the-object). +Cookie and device group variations come from the `modules.application_accelerator` object of the cache setting, the **Application Accelerator** section in Azion Console. Each copy they produce is an object under its own key, out of reach of a URL purge. For the purge by cache key or by the `@@*` wildcard that reaches it, refer to [A purge did not expire a copy of the object](/en/documentation/platform/applications/troubleshooting/#a-purge-did-not-expire-a-copy-of-the-object). -### A URL purge misses a query string variation +### A URL purge misses a copy that varies by query string -A URL purge reaches a query string variation only when it lists the arguments the key varies by, in the order the key stores them. That order is alphabetical when **Sort** is on in **Cache vary by Query String** in Azion Console, `sort_enabled` in the API. For that purge and the `?*` wildcard, refer to [A purge did not expire a variation of the object](/en/documentation/platform/applications/troubleshooting/#a-purge-did-not-expire-a-variation-of-the-object). +A URL purge reaches this copy only when it lists the arguments the key varies by, in the order the key stores them. That order is alphabetical when **Sort** is on in **Cache vary by Query String** in Azion Console, `sort_enabled` in the API. For that purge and the `?*` wildcard, refer to [A purge did not expire a copy of the object](/en/documentation/platform/applications/troubleshooting/#a-purge-did-not-expire-a-copy-of-the-object). ### A behavior or a variable cannot be selected in Rules Engine -In Azion Console, on the **Rules Engine** tab of an Application, a behavior such as _Bypass Cache_, _Forward Cookies_, or _Rewrite Request_ cannot be added to a rule. In the list, its name ends with `- Required Application Accelerator`, and the `${device_group}` variable is missing from the criteria. +A behavior such as _Bypass Cache_, _Forward Cookies_, or _Rewrite Request_ cannot be added to a rule. In Azion Console, on the **Rules Engine** tab of an Application, its name ends with `- Required Application Accelerator`, and the `${device_group}` variable is missing from the criteria. -Six behaviors and the `${device_group}` variable stay locked while Application Accelerator is off in the Application. +Eight behaviors and the `${request_uri}` and `${device_group}` variables require Application Accelerator turned on in the Application. - **Turn on Application Accelerator**: in Azion Console, its switch is in **Main Settings** › **Modules**. - **Turn on Functions for Run Function**: _Run Function_ depends on [Functions](/en/documentation/platform/functions/) turned on in the Application, not on Application Accelerator, as [Run Function is missing from the behaviors list](/en/documentation/platform/functions/troubleshooting/#run-function-is-missing-from-the-behaviors-list) explains. -A rule can then take the six behaviors, and its criteria can use `${device_group}`, as [Rules Engine behaviors](/en/documentation/platform/applications/application-accelerator/settings/#rules-engine-behaviors) lists by phase. +A rule can then take the eight behaviors, and its criteria can use `${request_uri}` and `${device_group}`, as [Rules Engine behaviors](/en/documentation/platform/applications/application-accelerator/settings/#rules-engine-behaviors) lists by phase. ### Content is served from cache with Bypass Cache configured -_Bypass Cache_ needs Application Accelerator, and a request that a _Bypass Cache_ rule matches can still be answered from the Tiered Cache layer, which [Bypass Cache](/en/documentation/platform/applications/cache/tiered-cache/#bypass-cache) leaves untouched. The rule works, so changing it fixes nothing: turn off Tiered Cache and purge both layers, as [Content is still served from cache after a Bypass Cache rule](/en/documentation/platform/applications/troubleshooting/#content-is-still-served-from-cache-after-a-bypass-cache-rule) describes. +_Bypass Cache_ needs Application Accelerator. A request that a _Bypass Cache_ rule matches can still be answered from the Tiered Cache layer, which [Bypass Cache](/en/documentation/platform/applications/cache/tiered-cache/#bypass-cache) leaves untouched. The rule works, so changing it fixes nothing: turn off Tiered Cache and purge both layers, as [Content is still served from cache after a Bypass Cache rule](/en/documentation/platform/applications/troubleshooting/#content-is-still-served-from-cache-after-a-bypass-cache-rule) describes. ### A cache variation is refused with error 21013 -Saving a cache setting returns `400` and code `21013` when it sets a variation in its **Application Accelerator** section in Azion Console, or a `behavior` other than `ignore` or a method in `modules.application_accelerator` in the API. [Errors](/en/documentation/platform/applications/cache/cache-settings/#errors) details the code. +Saving a cache setting returns `400` and code `21013` when the setting varies the key. In Azion Console, that is a variation in its **Application Accelerator** section, and in the API, a `behavior` other than `ignore` or a method in `modules.application_accelerator`. [Errors](/en/documentation/platform/applications/cache/cache-settings/#errors) details the code. A cache variation by method, query string, cookie, or device group needs Application Accelerator. @@ -325,7 +337,7 @@ Image Processor builds a derived image from the source image when a rule applies ### The image comes back untransformed although x-ims reads Enabled -A request with an `ims` query string returns the source image as it is, and the response carries `x-ims: Enabled`. +A request with the `ims` parameter returns the source image as it is, and the response carries `x-ims: Enabled`. Image Processor cannot parse the `ims` value, such as `450xOrig`, so it returns the source image without a transformation. `ims` can sit anywhere in the query string, so only its value decides the result. @@ -335,9 +347,9 @@ The URL then returns the derived image, with the transformation that the `ims` v ### The image is delivered unprocessed and its ims query string is ignored -The `ims` query string of a request is valid, yet the source image comes back as it is, without a resize, a crop, or a filter. +The `ims` parameter of a request is valid, yet the source image comes back as it is, without a resize, a crop, or a filter. -A transformation starts only when a rule matches the request and applies _Optimize Images_, whatever the `ims` query string asks for. +A transformation starts only when a rule matches the request and applies _Optimize Images_, whatever the `ims` parameter asks for. - **Check what the rule matches**: in Azion Console, on the **Rules Engine** tab of the Application, compare the rule's criterion with the request. A criterion for images compares `${uri}`, or `${request_uri}` with Application Accelerator on, through `matches` with an argument such as `\.(jpg|jpeg|gif|bmp|png|ico|webp|avif)`. - **Check the behavior**: _Optimize Images_ has to be a Request Phase behavior of the rule. When the rule also caches the result, _Set Cache Policy_ sits beside it, as [Rules Engine behaviors](/en/documentation/platform/applications/image-processor/settings/#rules-engine-behaviors) describes. @@ -364,7 +376,7 @@ A `filters:format()` filter returns the format it names whatever `Accept` header - **Check what the rule matches when the response has no `x-ims`**: no rule with _Optimize Images_ matches the request. [The image is delivered unprocessed and its ims query string is ignored](/en/documentation/platform/applications/troubleshooting/#the-image-is-delivered-unprocessed-and-its-ims-query-string-is-ignored) shows what the rule has to match. - **Check the `ims` value when the response carries `x-ims: Enabled`**: Image Processor cannot parse the value, as [The image comes back untransformed although x-ims reads Enabled](/en/documentation/platform/applications/troubleshooting/#the-image-comes-back-untransformed-although-x-ims-reads-enabled) describes. -Matching requests then get the image back as `image/webp` or `image/avif`, the format the `ims` string requests. +Matching requests then get the image back as `image/webp` or `image/avif`, the format the `ims` parameter requests. ### Every request for the same derived image reaches Image Processor diff --git a/apps/docs/src/content/docs/en/pages/build/cache/cache-keys.mdx b/apps/docs/src/content/docs/en/pages/build/cache/cache-keys.mdx index 6466811a18..d09a0d1283 100644 --- a/apps/docs/src/content/docs/en/pages/build/cache/cache-keys.mdx +++ b/apps/docs/src/content/docs/en/pages/build/cache/cache-keys.mdx @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -A cache key is the index entry [Cache](/en/documentation/platform/applications/cache/) stores an object under. Azion builds it from the request: the scheme, the host, the path, and the variations that a cache setting or [Image Processor](/en/documentation/platform/applications/image-processor/) adds. A request whose key matches a valid stored object is answered with that object. Otherwise the origin or a [Function](/en/documentation/platform/functions/) builds the response, and Azion can store that response under that key. For the lookup, refer to [Expiration and freshness](/en/documentation/platform/applications/cache/expiration-and-freshness/). For the fields that add variations, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/). +A cache key is the index entry [Cache](/en/documentation/platform/applications/cache/) stores an object under. Azion builds it from the request: the scheme, the host, the path, and the variations that a cache setting or [Image Processor](/en/documentation/platform/applications/image-processor/) adds. For how a request finds a stored object, and what happens when it finds none, refer to the [Cache overview](/en/documentation/platform/applications/cache/#request-path). For the fields that add variations, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/). --- @@ -28,23 +28,29 @@ The default key concatenates three elements of the request URI, in this order: The query string is not part of the default key: `https://static.example.com/page/site.js?city=city&name=name` produces the same key as the URI without it. The query-string variation under Variations adds it. -The URI `https://static.example.com/page/site.js` produces the key `httpsstatic.example.com/page/site.js`. Keys are case sensitive: upper and lower case characters are distinct. When a cache setting turns a variation on, the key can end with the `@@` separator, as in `httpsstatic.example.com/page/site.js@@`. The table under Variations shows where each variation goes: the request method is a prefix, and the other variations follow `@@`, the query string included when its behavior is `allowlist` or `denylist`. Under `all`, the whole query string follows the path, before `@@`. +The URI `https://static.example.com/page/site.js` produces the key `httpsstatic.example.com/page/site.js`. Keys are case sensitive: upper and lower case characters are distinct. + +When a cache setting turns a variation on, the key can end with the `@@` separator, as in `httpsstatic.example.com/page/site.js@@`. The table under Variations shows where each variation goes: the request method is a prefix, and the other variations follow `@@`, the query string included when its behavior is `allowlist` or `denylist`. Under `all`, the whole query string follows the path, before `@@`. --- ## Variations -A variation adds to the default key, so one URI can hold more than one object in the cache. The table lists what each variation adds and the key it produces. +A variation is an input of a request beyond its scheme, host, and path that varies the cache key. Each variation adds a marker to the default key, so one URI can hold a separate copy for each value of that input. The table lists what each variation adds and the key it produces. | Variation | What it adds | Example key | | --- | --- | --- | -| Complex request | The request method, prefixed to the key. A `GET` or `HEAD` request carries no prefix. | `optionshttpsstatic.example.com/page` | -| Query string | Under `allowlist` and `denylist`: `@@`, then `?` and the arguments the setting keeps. Under `all`: `?` and the whole query string, after the path and before `@@`. | `httpstatic.example.com/page@@?name=name`, `httpstatic.example.com/page?city=city&name=name@@` | -| Cookies | Under `allowlist` and `denylist`: `@@`, then each cookie name and value the setting keeps, followed by `;`. The empty variation, with no cookie value, is `@@;`. Under `all`, the whole `Cookie` header follows `@@` as it arrived, spaces included. | `httpwww.example.com/@@;`, `httpwww.example.com/@@user=user;` | -| Device group | `@@` and the name of the device group. | `httpwww.example.com/@@Mobile` | -| [Image Processor](/en/documentation/platform/applications/image-processor/) | The converted image format, at the end of the key with no separator. When the cache setting names `ims` in its query-string allowlist, the `ims` query string follows `@@`, and the format follows it. When the cache setting does not vary the key by query string, the `ims` value is not part of the key, so every size and processing of the path shares a key, and the first one stored answers every `ims` value. | `httpsstatic.example.com/static/images/image_1.jpg@@webp`, `httpsstatic.example.com/static/images/image_1.jpg@@?ims=880xwebp` | -| Large File Optimization | `@@bytes=-` for each fragment, so each fragment carries its own key. A file of 2,097,152 bytes produces two keys. | `httpsstatic.example.com/media/file.mp4@@bytes=0-1048575`, `httpsstatic.example.com/media/file.mp4@@bytes=1048576-2097151` | -| Cached `POST` | `@@` and the MD5 (Message Digest 5) hash of the request body, after the `post` prefix. A cached `OPTIONS` carries only the `options` prefix. | `posthttpsdynamic.example.com/path@@`, `optionshttpsdynamic.example.com/path` | +| Complex request | The request method, prefixed to the key | `optionshttpsstatic.example.com/page` | +| Query string | Under `allowlist` and `denylist`: `@@`, `?`, and the kept arguments. Under `all`: `?` and the whole query string, before `@@` | `httpstatic.example.com/page@@?name=name`, `httpstatic.example.com/page?city=city&name=name@@` | +| Cookies | Under `allowlist` and `denylist`: `@@`, then each kept cookie name and value, each followed by `;` | `httpwww.example.com/@@;`, `httpwww.example.com/@@user=user;` | +| Device group | `@@` and the name of the device group | `httpwww.example.com/@@Mobile` | +| [Image Processor](/en/documentation/platform/applications/image-processor/) | The converted image format, at the end of the key with no separator | `httpsstatic.example.com/static/images/image_1.jpg@@webp`, `httpsstatic.example.com/static/images/image_1.jpg@@?ims=880xwebp` | +| Large File Optimization | `@@bytes=-`, one key for each fragment | `httpsstatic.example.com/media/file.mp4@@bytes=0-1048575`, `httpsstatic.example.com/media/file.mp4@@bytes=1048576-2097151` | +| Cached `POST` | `@@` and the MD5 (Message Digest 5) hash of the request body, after the `post` prefix | `posthttpsdynamic.example.com/path@@`, `optionshttpsdynamic.example.com/path` | + +A `GET` or `HEAD` request carries no method prefix, and a cached `OPTIONS` carries only the `options` prefix. The empty cookie variation, with no cookie value, is `@@;`. Under `all`, the whole `Cookie` header follows `@@` as it arrived, spaces included. A file of 2,097,152 bytes produces two fragment keys. + +When the cache setting names `ims` in its query-string allowlist, the `ims` query string follows `@@`, and the image format follows it. When the cache setting does not vary the key by query string, the `ims` value is not part of the key. Every size and processing of the path then shares a key, and the first one stored answers every `ims` value. The query-string and cookie fields are case sensitive, so `user` and `User` are two variations. With `sort_enabled` on in the cache setting, `?name=name&city=city` and `?city=city&name=name` share one key, with the arguments in alphabetical order. @@ -72,7 +78,9 @@ x-cache: MISS from 192.0.2.10 with HTTP/2.0 x-cache-key: httpsstatic.example.com/page/site.js ``` -Under HTTP/2, the header names arrive in lower case. A `GET` or `HEAD` response that Azion does not store carries `-` in both headers while Application Accelerator is on; with it off, the same response reports `MISS`, with its key in `x-cache-key` and `x-cache-expires-in: 0`. A `POST`, `PUT`, `PATCH`, `DELETE`, or `OPTIONS` response that Azion does not store carries `-` either way. Consecutive requests for one path can each be answered by a different server, which `x-cache` names. For the procedure, refer to [Check the cache status of a response](/en/documentation/guides/application-performance/cache-and-purge/check-page-cache-time/). +Under HTTP/2, the header names arrive in lower case. A `GET` or `HEAD` response that Azion does not store carries `-` in both headers while Application Accelerator is on. With Application Accelerator off, the same response reports `MISS`, with its key in `x-cache-key` and `x-cache-expires-in: 0`. + +A `POST`, `PUT`, `PATCH`, `DELETE`, or `OPTIONS` response that Azion does not store carries `-` either way. Consecutive requests for one path can each be answered by a different server, which `x-cache` names. For the procedure, refer to [Check the cache status of a response](/en/documentation/guides/application-performance/cache-and-purge/check-page-cache-time/). --- diff --git a/apps/docs/src/content/docs/en/pages/build/cache/how-it-works.mdx b/apps/docs/src/content/docs/en/pages/build/cache/how-it-works.mdx index 45be01392c..5a22387a39 100644 --- a/apps/docs/src/content/docs/en/pages/build/cache/how-it-works.mdx +++ b/apps/docs/src/content/docs/en/pages/build/cache/how-it-works.mdx @@ -9,7 +9,9 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -The time a cached copy answers for the origin decides two things: how fresh a response is, and how often the origin is asked. In an Application, [Cache](/en/documentation/platform/applications/cache/) is the Platform Resource that stores the copy, and a [cache setting](/en/documentation/platform/applications/cache/cache-settings/) sets that time as its time to live (TTL). The cache setting also decides what happens after the TTL ends. A purge ends a copy early. The [Cache overview](/en/documentation/platform/applications/cache/#request-path) shows how a request reaches a cached copy, with a diagram of the cache path. +The time a cached copy answers for the origin decides two things: how fresh a response is, and how often the origin is asked. In an Application, [Cache](/en/documentation/platform/applications/cache/) is the Platform Resource that stores the copy. A [cache setting](/en/documentation/platform/applications/cache/cache-settings/), a set of values that tell Cache how to store and serve a response, sets that time as the copy's time to live (TTL). + +The cache setting also decides what happens after the TTL ends, and a purge ends a copy early. The [Cache overview](/en/documentation/platform/applications/cache/#request-path) shows how a request reaches a cached copy, with a diagram of the cache path. The sections cover TTL and expiration, stale cache, Large File Optimization, cache keys and variations, Tiered Cache, and purge. @@ -19,13 +21,17 @@ The sections cover TTL and expiration, stale cache, Large File Optimization, cac A cache setting carries two TTLs. The browser TTL controls how long a visitor's browser keeps its copy. The cache TTL controls how long Azion keeps its own. A request that the browser answers from its copy stops at the browser, and a request that Azion answers from its copy stops at Azion. -Where each TTL comes from depends on the behavior the setting selects for each copy. For Azion's copy, the behavior is the `modules.cache.behavior` field. _Honor cache policies_ (`honor`) keeps the `Cache-Control` and `Expires` headers of the origin and forwards them to the browser, so the origin decides how long its content lives. _Override cache behavior_ (`override`) replaces those headers for Azion's cache with Max Age, the `modules.cache.max_age` field. When the origin sends no TTL under _Honor cache policies_, Azion keeps the copy for the Max Age of the setting. The browser's copy has its own behavior in the `browser_cache.behavior` field: _Honor cache policies_, _Override cache settings_, or _No cache_. +Where each TTL comes from depends on the behavior the setting selects for each copy. For Azion's copy, the behavior is the `modules.cache.behavior` field. _Honor cache policies_ (`honor`) keeps the `Cache-Control` and `Expires` headers of the origin and forwards them to the browser, so the origin decides how long its content lives. + +_Override cache behavior_ (`override`) replaces those headers for Azion's cache with Max Age, the `modules.cache.max_age` field. When the origin sends no TTL under _Honor cache policies_, Azion keeps the copy for the Max Age of the setting. The browser's copy has its own behavior in the `browser_cache.behavior` field: _Honor cache policies_, _Override cache settings_, or _No cache_. -The copy expires when the cache TTL ends, and the next request for the object goes to the origin. When the origin returns the object, that response updates the copy. The response reports `EXPIRED`. A check with conditional headers can also find the copy unchanged. The response then reports `REVALIDATED`, and the origin confirms the copy instead of sending the object again. +The copy expires when the cache TTL ends, and the next request for the object goes to the origin. When the origin returns the object, that response updates the copy, and the response reports `EXPIRED`. A check with conditional headers can also find the copy unchanged. The response then reports `REVALIDATED`, and the origin confirms the copy instead of sending the object again. A request that finds no valid copy is a cache miss. On a miss, the platform limits the work of the origin. When several requests for the same uncached object reach the same server at the same time, that server opens one connection to the origin for all of them. So, under a burst of requests for an uncached object, the origin sees one fetch per server that received the burst, not one per visitor. -The TTL is a trade between the load on the origin and the age of what a visitor sees. A long TTL answers more requests from the copy and reaches the origin less, but content the origin already changed stays in the copy until it expires. A short TTL keeps the copy close to the origin's version, at the price of more origin fetches. For example, one Application can hold two cache settings, each applied by its own rule. Images that rarely change take a TTL of a day, and a listing that changes through the day takes a TTL of a few minutes. +The TTL is a trade between the load on the origin and the age of what a visitor sees. A long TTL answers more requests from the copy and reaches the origin less, but content the origin already changed stays in the copy until it expires. A short TTL keeps the copy close to the origin's version, at the price of more origin fetches. + +For example, one Application can hold two cache settings, each applied by its own rule. Images that rarely change take a TTL of a day, and a listing that changes through the day takes a TTL of a few minutes. Max Age has a floor and a ceiling, and [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) lowers the floor. For every TTL bound, refer to [Applications limits](/en/documentation/platform/applications/limits/#cache-settings). For how a TTL of 0 seconds differs from bypassing the cache, refer to [Bypass Cache and a TTL of 0](/en/documentation/platform/applications/application-accelerator/cache-variation/#bypass-cache-and-a-ttl-of-0). @@ -39,9 +45,7 @@ A copy past its TTL still has a use. With stale cache on in the cache setting, A - The connection times out, or the origin is unreachable. - The cache-control headers of the origin are invalid or missing. -How long the expired copy may be served is the stale window. Under _Honor cache policies_, the window is the value of the `stale-while-revalidate=` directive the origin supplies. Under _Override cache behavior_, or when the origin omits the directive, the window is 300 seconds. - -A response served from an expired copy because the origin failed to respond reports `STALE`. +How long the expired copy may be served is the stale window. Under _Honor cache policies_, the window is the value of the `stale-while-revalidate=` directive the origin supplies. Under _Override cache behavior_, or when the origin omits the directive, the window is 300 seconds. A response served from an expired copy because the origin failed to respond reports `STALE`. Stale cache shows visitors an old page instead of an error page during an origin outage, for as long as the window lasts. The cost is freshness: a visitor inside the window can receive content the origin already replaced. So a change that every visitor has to see at once is a case for a purge rather than for expiry. @@ -51,7 +55,9 @@ Whether stale cache starts on in a new setting depends on the interface. Its fie ## Large File Optimization -A large object can be cached in fragments rather than as one piece. With Large File Optimization on in the cache setting, in its `modules.cache.large_file_cache.enabled` field, Azion splits the file into fragments of 1,024 kB. Each fragment is delivered as the user consumes it, and it is cached on demand, at the moment it is requested. The cache key of a fragment ends in `@@bytes=` and the byte range of the fragment. So every fragment is an object of its own. +A large object can be cached in fragments rather than as one piece. With Large File Optimization on in the cache setting, in its `modules.cache.large_file_cache.enabled` field, Azion splits the file into fragments of 1,024 kB. Each fragment is delivered as the user consumes it, and it is cached on demand, at the moment it is requested. + +Each fragment gets its own cache key, the index entry Cache stores a copy under. The key of a fragment ends in `@@bytes=` and the byte range of the fragment, so every fragment is an object of its own. For example, a video of 2,097,151 bytes at `https://static.example.com/media/file.mp4` becomes two fragments. They are stored under these keys: @@ -68,7 +74,9 @@ The cost comes at purge time. One file becomes many keys, so a purge lists the k ## Cache keys and variations -A variation is a further copy of one path, stored under its own cache key because something other than the path differs. While no variation is on, one path is one stored object. Azion builds the default key from the scheme, the host, and the path of the request. A cache setting holds its query-string variation in the `cache_vary_by_querystring.behavior` field, which starts at `ignore` and keeps the query string out of the key. When something other than the path changes the response, the cache setting names it, and the key carries a marker for it. +A variation is an input of a request beyond its scheme, host, and path that varies the cache key. Cache keeps a separate copy for each value of a variation, under its own cache key. While no variation is on, one path is one stored object, and Azion builds the default key from the scheme, the host, and the path of the request. + +A cache setting holds its query-string variation in the `cache_vary_by_querystring.behavior` field, which starts at `ignore` and keeps the query string out of the key. When something other than the path changes the response, the cache setting names it, and the key carries a marker for it. Four inputs can vary a copy through the `modules.application_accelerator` object of a cache setting: @@ -77,25 +85,52 @@ Four inputs can vary a copy through the `modules.application_accelerator` object - The device group a request falls in. - The request method. -Two more come from elsewhere. [Image Processor](/en/documentation/platform/applications/image-processor/) adds the image format when it converts an image, and Large File Optimization adds the byte range of each fragment. Each distinct value is a separate key, so each one is stored and purged separately. +Two more come from elsewhere. [Image Processor](/en/documentation/platform/applications/image-processor/) adds the image format when it converts an image, and Large File Optimization adds the byte range of each fragment. Device groups belong to the Application, and [Device Groups](/en/documentation/platform/applications/device-groups/) documents them. With `cache_vary_by_devices`, a setting delivers one version whatever the device, or keeps one copy per named group. The method is a variation too. `GET` and `HEAD` responses are cached natively, and `POST` and `OPTIONS` responses are cached only with Application Accelerator on and the method listed in `cache_vary_by_method`. The body of a `POST` then becomes part of the key as an MD5 hash, so two different bodies posted to one path are two objects. An `OPTIONS` key carries the method prefix only. -A variation splits the requests for one path across several copies. Fewer requests find a copy already present, and a purge has to reach every copy. For example, a listing page that varies by a `page` argument stores one copy per page number, and a purge of the listing has to name each of them. For the marker each variation appends, refer to [Cache keys](/en/documentation/platform/applications/cache/cache-keys/#variations). For the fields that turn a variation on, refer to [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/#cache-variation). +A variation splits the requests for one path across several copies. Fewer requests find a copy already present, and a purge has to reach every copy. For example, a listing page that varies by a `page` argument stores one copy per page number, and a purge of the listing has to name each of them. + +For the marker each variation appends, refer to [Cache keys](/en/documentation/platform/applications/cache/cache-keys/#variations). For the fields that turn a variation on, refer to [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/#cache-variation). --- ## Tiered Cache -[Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) is a Feature of Cache that adds a second cache layer between the data center that answers a request and the origin. When that data center holds no valid copy, it asks the Tiered Cache layer before the request goes to the origin. A valid copy in that layer answers the miss, and the origin receives no request. +[Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) is a Feature of Cache that adds a second cache layer between the data center that answers a request and the origin. + +Solid arrows carry the request, and dotted arrows carry the response. Each label starts with the number of its step below. + +```mermaid +%%{init: {"layout": "elk", "elk": {"cycleBreakingStrategy": "MODEL_ORDER"}, "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% +flowchart TD + Client(["Client"]) + DC["data center: first layer"] + Tier["Tiered Cache layer"] + Origin[["origin server"]] + Client -->|"1. request"| DC + DC -->|"2. no valid copy"| Tier + Tier -.->|"3. valid copy"| DC + Tier -->|"4. no valid copy"| Origin + Origin -.->|"4. response"| Tier + Tier -.->|"4. response"| DC + DC -.->|"1, 3, 4. response"| Client +``` + +1. The request reaches the data center that answers it, which responds from its own cache when it holds a valid copy. +2. When that data center holds no valid copy, it asks the Tiered Cache layer. +3. A valid copy in the Tiered Cache layer answers the miss, and the origin receives no request. +4. Otherwise, the request goes to the origin, and the response returns to the data center through the Tiered Cache layer. Each cache setting turns the layer on in its `modules.cache.tiered_cache.enabled` field, and every plan includes it. The setting names a topology in `modules.cache.tiered_cache.topology`: the region that holds the layer, such as `nearest-region` or `us-east-1`. Tiered Cache also requires _Override cache behavior_. Under _Honor cache policies_, the API refuses the setting with `21001`. -The trade is an extra hop and a floor on the TTL. A miss in the first layer travels to the second before it reaches the origin. A setting with Tiered Cache on also carries a minimum TTL. In return, fewer requests reach the origin. For the minimum, refer to [Applications limits](/en/documentation/platform/applications/limits/#cache-settings). +The trade is an extra hop and a floor on the TTL. A miss in the first layer travels to the second before it reaches the origin. In return, an answer from the Tiered Cache layer arrives with less latency than one from the origin, and fewer requests reach the origin, so the origin handles less load at a lower infrastructure cost. For the minimum TTL, refer to [Applications limits](/en/documentation/platform/applications/limits/#cache-settings). -A _Bypass Cache_ rule affects Azion's cache and not the Tiered Cache layer. An Application with active Tiered Cache settings keeps caching objects in that layer for the Max Age of the cache setting. The layer is purged by cache key. When you purge an object held in both layers, purge the Tiered Cache layer first and then Cache, or the first layer refills from stale Tiered Cache content. For the purge layers, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#layers). +A _Bypass Cache_ rule affects Azion's cache and not the Tiered Cache layer. An Application with active Tiered Cache settings keeps caching objects in that layer for the Max Age of the cache setting. + +The Tiered Cache layer is purged by cache key, and the order of the purges decides what the first layer holds. When Cache is purged before the Tiered Cache layer, the first layer refills from stale Tiered Cache content. So an object held in both layers leaves the Tiered Cache layer first, then Cache. For the purge layers, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#layers). --- @@ -103,9 +138,15 @@ A _Bypass Cache_ rule affects Azion's cache and not the Tiered Cache layer. An A A purge removes a stored copy before its TTL ends. Once no layer holds a copy, the next request for the object goes to the origin, the response reports `MISS`, and the version the origin returns is stored. A purge is queued after you confirm it, because the result takes time to propagate. It appears in the purge history once it completes across Azion's infrastructure. -A purge finds an object by its cache key, so the purge type matters for an object that varies. A URL purge converts each URL to a cache key without considering content variation. So a copy that varies by cookie, device group, or image format survives it. A cache key purge names each variation. A wildcard purge reaches every key that matches an expression with `*`. Query-string variations are the exception a URL purge does reach. The arguments have to be sent in the order they were presented, or in alphabetical order when the cache setting sorts them, in its `cache_vary_by_querystring.sort_enabled` field. +A purge finds an object by its cache key, so the purge type matters for an object that varies. Each of the three purge types reaches a different set of keys: + +- A URL purge converts each URL to a cache key without considering content variation, so a copy that varies by cookie, device group, or image format survives it. +- A cache key purge names the key of each copy. +- A wildcard purge reaches every key that matches an expression with `*`. + +Query-string variations are the exception a URL purge does reach. The arguments have to be sent in the order they were presented, or in alphabetical order when the cache setting sorts them, in its `cache_vary_by_querystring.sort_enabled` field. -A purge is the tool for a change that cannot wait for the TTL. Its cost is the origin fetch that refills each purged key. The more keys an object has, through variations or fragments, the more a purge has to name. For the purge types and their arguments, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/). For the steps, refer to [Purge cached content](/en/documentation/guides/application-performance/cache-and-purge/purge-cached-content/). +A purge is the tool for a change that cannot wait for the TTL. Its cost is the origin fetch that refills each purged key, one per fragment or per copy of a variation. For the purge types and their arguments, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/). For the steps, refer to [Purge cached content](/en/documentation/guides/application-performance/cache-and-purge/purge-cached-content/). --- diff --git a/apps/docs/src/content/docs/en/pages/build/cache/overview.mdx b/apps/docs/src/content/docs/en/pages/build/cache/overview.mdx index d8aad994c8..de92d6d8a3 100644 --- a/apps/docs/src/content/docs/en/pages/build/cache/overview.mdx +++ b/apps/docs/src/content/docs/en/pages/build/cache/overview.mdx @@ -10,20 +10,21 @@ import DocButton from '~/components/webkit/DocButton.vue' import DocCardGroup from '@aziontech/webkit/doc-card-group' import DocCard from '@aziontech/webkit/doc-card' -**Cache** is a Platform Resource that stores copies of the responses to the requests received by your [Applications](/en/documentation/platform/applications/), on Azion's distributed infrastructure. A cache is a store of response copies between clients and the origin, the server that holds the content. It answers repeated requests with those copies. +**Cache** is a Platform Resource that stores copies of responses to the requests received by your [Applications](/en/documentation/platform/applications/), from the data center nearest to your user. A cache is a store of response copies, kept between clients and the origin server, that answers repeated requests without asking the origin. Cache can also remove stored copies on demand with [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/). Use Cache to serve static files, large videos in fragments, and expired copies during an origin outage. -The first request for an object reaches the origin, and the cache stores the response under a key built from the request. Later requests with the same key get the stored copy. The copy lasts until its time to live (TTL), a period in seconds, ends. The origin then answers only the first request and the requests that arrive after the copy expires. +In each Application, Cache can use these nested resources and features: -Cache is always on in an Application. It stores only the responses to the requests that a [Rules Engine](/en/documentation/platform/applications/rules-engine/) rule with the _Set Cache Policy_ behavior matches. That rule applies a [cache setting](/en/documentation/platform/applications/cache/cache-settings/), which holds the TTLs and decides how Azion stores and varies each copy. Cache can store a response whether the origin or a [Function](/en/documentation/platform/functions/) builds it. Each copy stays in the data center that stored it. Use Cache to keep static files in the data center nearest to your user, serve large videos in fragments with Large File Optimization, answer with an expired copy through stale cache while the origin is down, or remove a copy with [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/) when the origin changes. +- [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/) lets you serve an update the origin already has before a copy's time to live (TTL) ends. Use it to remove an obsolete object, or to control what Azion serves for dynamic content. +- [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) lets an Application answer a cache miss from a second cache layer before the request reaches the origin. The origin then receives fewer requests and carries less load. - + --- ## Request path -Creating a cache setting caches nothing: a request reaches a stored copy only through a rule that applies the setting. +Creating a cache setting caches nothing: a request reaches a stored copy only through a rule that applies the setting. A cache setting is a set of values that tell Cache how to store and serve a response, such as its TTLs. Cache itself is on in every Application, so that rule is the one step a copy needs. Solid arrows carry the request, and dotted arrows carry the response. Each label starts with the number of its step below. @@ -48,59 +49,12 @@ flowchart TD ``` 1. The client's request reaches an Application, and the Application's Request Phase rules run in order. -2. When a _Set Cache Policy_ rule applies a cache setting, Cache builds the cache key from the request and from every variation the setting names. -3. When Cache holds a valid copy under that key, the data center that received the request answers from it. The response reports `HIT`. -4. Otherwise, the Connector that a _Set Connector_ rule sets routes the request to the origin, and the response reports `MISS`. Cache may store the response under the key for later requests. -5. When no rule applies a cache setting, or a _Bypass Cache_ rule matches, the request goes to the origin past Cache. _Bypass Cache_ requires [Application Accelerator](/en/documentation/platform/applications/application-accelerator/). With _Bypass Cache_, nothing is stored, and the response reports `-` or `BYPASS` in `x-cache`. +2. When a rule with _Set Cache Policy_ applies a cache setting, Cache builds the cache key from the request and from every variation the setting names. +3. When Cache holds a valid copy under that key, the data center that received the request answers from it, because each copy stays in the data center that stored it. The response reports `HIT`. +4. Otherwise, the Connector that a rule with _Set Connector_ sets routes the request to the origin, and the response reports `MISS`. Cache may store the response under the key for later requests. +5. When no rule applies a cache setting, or a rule with _Bypass Cache_ matches, the request goes to the origin past Cache. _Bypass Cache_ requires [Application Accelerator](/en/documentation/platform/applications/application-accelerator/). With _Bypass Cache_, Azion's cache stores no copy, and the response reports `-` or `BYPASS` in `x-cache`. -A stored copy answers until its TTL ends or a purge removes it. The status comes back in the `x-cache` header of a response to a request sent with `Pragma: azion-debug-cache`. For every status and the debug headers, refer to [Cache keys](/en/documentation/platform/applications/cache/cache-keys/#cache-status). - -For TTL and expiration, stale cache, Large File Optimization, cache keys and variations, Tiered Cache, and purge, refer to [Expiration and freshness](/en/documentation/platform/applications/cache/expiration-and-freshness/). - ---- - -## Cache setting structure - -Cache acts through a cache setting. The setting holds how long Azion and the browser keep a copy, what Azion does with an expired copy, and what makes two requests different. To keep each response for 300 seconds in Azion's cache and for one day in the browser, send this cache setting as the body of `POST /v4/workspace/applications//cache_settings`: - -```json -{ - "name": "static-assets", - "browser_cache": { "behavior": "override", "max_age": 86400 }, - "modules": { - "cache": { - "behavior": "override", - "max_age": 300, - "stale_cache": { "enabled": true }, - "large_file_cache": { "enabled": true, "offset": 1024 }, - "tiered_cache": { "enabled": true, "topology": "nearest-region" } - } - } -} -``` - -- `browser_cache` decides what a visitor's browser keeps. `honor` forwards the `Cache-Control` and `Expires` headers of the origin. `override` replaces them with `max_age`, in seconds. `no-cache` turns browser caching off. -- `modules.cache` decides what Azion keeps. With `behavior` set to `override`, `max_age` replaces the headers of the origin. Under `honor`, Azion keeps those headers. When the origin sends no TTL, Azion keeps the response for the `max_age` of the setting. -- `stale_cache`, `large_file_cache`, and `tiered_cache` turn on stale cache, fragments of 1,024 kB, and a second cache layer in the region that `topology` names. Stale cache can serve an expired copy when Azion cannot confirm the copy with the origin. A body that leaves one of the three fields out gets that field off. `tiered_cache` also requires the `override` behavior. -- A cache setting acts only once a Request Phase rule applies that cache setting with `{ "type": "set_cache_policy", "attributes": { "value": } }`. You can also build the same setting in Azion Console, as [Cache quickstart](/en/documentation/platform/applications/cache/quickstart/) shows. - -If you set `Cache-Control` headers at your origin, the model transfers: `honor` keeps them, and `override` replaces them. - ---- - -## Scope and limits - -- **Application**: Cache is always on in an Application, in its `modules.cache.enabled` field in the API, which refuses `false` with `31001`. [Main Settings](/en/documentation/platform/applications/main-settings/#platform-resources) shows its switch locked on in Azion Console, with the note `Automatically enabled in all accounts.` A new Application has no cache settings and no rules, so Cache starts storing copies once a _Set Cache Policy_ rule applies a cache setting. -- **Expired copies**: with stale cache on, in the `modules.cache.stale_cache.enabled` field of a cache setting, Azion may serve an expired copy when it cannot confirm the copy with the origin. The response then reports `STALE`. A setting created through [Azion API](https://api.azion.com/) or [Azion CLI](/en/documentation/devtools/cli/) has it off, while Azion Console turns it on for a new setting. [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#cache) shows where to change it in each interface. For when an old page is better than an error, refer to [Applications best practices](/en/documentation/platform/applications/best-practices/#cache). -- **Large files**: Large File Optimization, the `modules.cache.large_file_cache.enabled` field of a cache setting, caches a large object in fragments of 1,024 kB. It is off in a new cache setting. Each fragment is fetched when a user reaches it and stored under a key of its own, so a purge of the file has to name every fragment or use a wildcard. -- **Tiered Cache**: [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) is a Feature of Cache that adds a second cache layer between the data center that answers a request and the origin. Each cache setting turns it on in its `modules.cache.tiered_cache.enabled` field, and every plan includes it. A data center that holds no valid copy asks that layer before the request goes to the origin. Tiered Cache requires the `override` behavior and a minimum TTL. A _Bypass Cache_ rule acts on Azion's cache only, so the Tiered Cache layer keeps caching objects for the Max Age of the cache setting. -- **Keys and variation**: Azion builds the default [cache key](/en/documentation/platform/applications/cache/cache-keys/) from the scheme, the host, and the path, so one path is one stored object, and the query string stays out of the key. Varying a copy by query string, cookie, device group, or method takes [Application Accelerator](/en/documentation/platform/applications/application-accelerator/). [Image Processor](/en/documentation/platform/applications/image-processor/) adds the format of a converted image to the key. -- **Purge**: [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/) is a Platform Resource that removes a stored copy before its TTL ends, by URL, by cache key, or by wildcard. Azion queues a purge after you confirm it, because the result takes time to propagate. The purge history lists the purge once it completes. A copy that varies by cookie, device group, or image format survives a URL purge, and a cache key or wildcard purge reaches it. -- **Code**: code that reads and writes cached entries runs in a [Function](/en/documentation/platform/functions/) and calls [Cache API](/en/documentation/devtools/runtime/api-reference/cache/), because Cache itself cannot run code. -- **Interfaces**: you create cache settings on the **Cache Settings** tab of an Application in Azion Console, through Azion API at `/v4/workspace/applications//cache_settings`, and with Azion CLI commands such as `azion create cache-setting`. [`azion.config.js`](/en/documentation/devtools/cli/azion-config-js/) declares a setting as an entry of its `cache` array, [Azion Lib](/en/documentation/devtools/azion-lib/application/) creates one with `createCacheSetting`, and [Azion Terraform Provider](/en/documentation/devtools/terraform/applications/) manages one with the `azion_application_cache_setting` resource. A purge is sent from **Real-Time Purge** in Azion Console, to `POST /v4/workspace/purge/`, or with `azion purge`. -- **Observability**: a request sent with `Pragma: azion-debug-cache` receives two headers. `x-cache` carries the cache status, and `x-cache-key` carries the key of the copy. [Real-Time Metrics](/en/documentation/platform/real-time-metrics/) shows Cache and Tiered Cache traffic, and [Real-Time Events](/en/documentation/platform/real-time-events/) carries a Tiered Cache dataset. -- **Limits**: a single cached object can reach 10 GB. Max Age, the `modules.cache.max_age` field of a cache setting, takes 60 seconds to one year. With Application Accelerator on, Azion API accepts down to 0 seconds. For every bound of a cache setting, a cached object, and a purge request, refer to [Applications limits](/en/documentation/platform/applications/limits/#cache). For the rates, refer to [Pricing](/en/documentation/fundamentals/pricing/#cache), and for what each plan includes, to [Azion pricing](https://www.azion.com/en/pricing/). -- **Terms**: the [Applications glossary](/en/documentation/platform/applications/glossary/) defines the words the Cache pages give a specific meaning, such as cache setting, cache key, cache status, and stale cache. +A stored copy answers until its TTL, a period in seconds, ends. Cache stores a response whether the origin or a [Function](/en/documentation/platform/functions/) builds it. The status comes back in the `x-cache` header of a response to a request sent with `Pragma: azion-debug-cache`. For every status and the debug headers, refer to [Cache keys](/en/documentation/platform/applications/cache/cache-keys/#cache-status). --- @@ -108,9 +62,11 @@ If you set `Cache-Control` headers at your origin, the model transfers: `honor` - + + - + + diff --git a/apps/docs/src/content/docs/en/pages/build/cache/quickstart.mdx b/apps/docs/src/content/docs/en/pages/build/cache/quickstart.mdx index 015849f21a..6da493b5eb 100644 --- a/apps/docs/src/content/docs/en/pages/build/cache/quickstart.mdx +++ b/apps/docs/src/content/docs/en/pages/build/cache/quickstart.mdx @@ -21,7 +21,7 @@ This guide instructs you through caching a path of your Application for the firs - A [Rules Engine](/en/documentation/platform/applications/rules-engine/) rule that applies the setting to one path prefix. - The cache status of a response, read from its `x-cache` header. -The result rests on four objects, in this order. The **Application** has [Cache](/en/documentation/platform/applications/cache/) on, as every Application does. The **cache setting** belongs to the Application. It holds the time to live (TTL), how long Azion keeps a copy. It also holds what Azion does with that copy. +The result rests on an Application, a cache setting, a rule, and a request, in this order. The **Application** has [Cache](/en/documentation/platform/applications/cache/) on, as every Application does. The **cache setting** belongs to the Application. It is a set of values that tell Cache how to store and serve a response, such as the time to live (TTL), how long Azion keeps a copy. The **rule**, also on the Application, matches requests by path and applies the setting through the _Set Cache Policy_ behavior. A cache setting acts only once a rule applies that cache setting. A matching **request** is answered from the stored copy when one exists. With the `Pragma: azion-debug-cache` header, its response reports `HIT` in `x-cache`. @@ -73,7 +73,7 @@ The **rule**, also on the Application, matches requests by path and applies the ## Create a cache setting -A cache setting holds how long Azion keeps a copy of a response, and what Azion does with that copy. This one keeps each copy for 300 seconds. +A cache setting is a set of values that tell Cache how to store and serve a response. This one keeps each copy for 300 seconds. @@ -86,7 +86,7 @@ To create the cache setting in Azion Console: - Access [Azion Console](https://console.azion.com/) > **Applications**, then select the Application that serves your content. + Access [Azion Console](https://console.azion.com/) > **Applications** > your Application. @@ -150,9 +150,9 @@ To create the cache setting with the Azion CLI, replace `` with - Replace `123460` with the ID the create command returned: + Replace `` with the ID the create command returned: - --cache-setting-id 123460 --format json`} /> + --cache-setting-id --format json`} /> The output reports `modules.cache.max_age` as `300`. @@ -250,7 +250,7 @@ To create the rule in Azion Console: - Access [Azion Console](https://console.azion.com/) > **Applications**, then select the Application that serves your content. + Access [Azion Console](https://console.azion.com/) > **Applications** > your Application. @@ -409,7 +409,7 @@ A new rule can take a few minutes to propagate. Wait before you check the cache ## Check the cache status -The request header `Pragma: azion-debug-cache` makes the response carry two debug headers. `x-cache` holds the cache status, the IP of the server that answered, and the protocol. `x-cache-key` holds the key that indexes the copy. +To read the cache status, request an object with the `Pragma: azion-debug-cache` header: its response carries two debug headers. The `x-cache` header holds the cache status, the IP of the server that answered, and the protocol. The `x-cache-key` header holds the key that indexes the copy. @@ -434,7 +434,12 @@ The request header `Pragma: azion-debug-cache` makes the response carry two debu - A response answered from the stored copy carries `HIT`. `x-cache` also names the server that answered. Each server keeps its own copy, so a request that another server answers can report `MISS` once more. Run the command again. + A response answered from the stored copy carries `HIT`. `x-cache` also names the server that answered. Each server keeps its own copy, so a request that another server answers can report `MISS` once more. + + + + + If the response reports `MISS`, run the command again. diff --git a/apps/docs/src/content/docs/en/pages/build/image-processor/how-it-works.mdx b/apps/docs/src/content/docs/en/pages/build/image-processor/how-it-works.mdx index 18d5a739df..d69479d68b 100644 --- a/apps/docs/src/content/docs/en/pages/build/image-processor/how-it-works.mdx +++ b/apps/docs/src/content/docs/en/pages/build/image-processor/how-it-works.mdx @@ -9,7 +9,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -An image built on request still has to reach the browser in a format it reads, and be built once rather than for every reader. In an [Application](/en/documentation/platform/applications/), [Image Processor](/en/documentation/platform/applications/image-processor/) is the Platform Resource that builds that image, the derived image, from the source image on the origin. How a request becomes a derived image, with the diagram of that chain, is on the [Image Processor overview](/en/documentation/platform/applications/image-processor/#request-path). +An image built on request still has to reach the browser in a format it reads, and be built once rather than for every reader. In an [Application](/en/documentation/platform/applications/), [Image Processor](/en/documentation/platform/applications/image-processor/) is the Platform Resource that builds that image, the derived image. It builds it from the file on the origin, the source image. How a request becomes a derived image, with the diagram of that chain, is on the [Image Processor overview](/en/documentation/platform/applications/image-processor/#request-path). The sections cover how the delivered format is chosen, how the cache tells one derived image from another, and where Image Processor stops. @@ -19,9 +19,11 @@ The sections cover how the delivered format is chosen, how the cache tells one d The delivered format can differ from the format of the source image. Two mechanisms change it, and they behave differently. -The first is explicit. A `filters:format()` filter in the `ims` string asks for a named output format, and the response carries that format whatever `Accept` header the request sent, or with none. +The first is explicit. A `filters:format()` filter in the `ims` query-string parameter asks for a named output format, and the response carries that format whatever `Accept` header the request sent, or with none. -The second is automatic and needs no `ims` parameter at all. Image Processor detects which formats the browser supports and, when possible, converts the image to one of them, such as WEBP or AVIF. A BMP image is converted to JPEG or WEBP depending on the same support. For example, a request whose `Accept` header lists `image/webp`, with no query string, can receive `image/webp` for a source image stored as PNG. A response can carry a format other than the one on the origin even when the URL has no filter. +The second is automatic and needs no `ims` parameter at all. Image Processor detects which formats the browser supports and, when possible, converts the image to one of them, such as WEBP or AVIF. A BMP image is converted to JPEG or WEBP depending on the same support. + +For example, a request whose `Accept` header lists `image/webp`, with no query string, can receive `image/webp` for a source image stored as PNG. So the bytes on the origin and the bytes on the wire are two different measurements, and the response says so. A processed response carries `x-ims: Enabled`, and `x-original-image-size` carries the size of the source image before the transformation. Read these headers before you compare a response with the file on the origin. For the headers, refer to [Image Processor settings](/en/documentation/platform/applications/image-processor/settings/#response-headers). @@ -29,7 +31,9 @@ So the bytes on the origin and the bytes on the wire are two different measureme ## One cache entry per transformation -A derived image is worth building only once. The practice for the cache setting that serves images is to vary the cache on `ims`: its `cache_vary_by_querystring` field takes the `allowlist` behavior, with `ims` in `fields`. Each distinct `ims` string then has a cache key of its own. That field sits under `modules.application_accelerator` in the cache setting, so varying the cache on `ims` requires [Application Accelerator](/en/documentation/platform/applications/application-accelerator/), while processing an image does not. [Image Processor settings](/en/documentation/platform/applications/image-processor/settings/#cache-variation) maps each of these fields to its control in Azion Console. +A derived image is worth building only once. The practice for the cache setting that serves images is to vary the cache on `ims`: its `cache_vary_by_querystring` field takes the `allowlist` behavior, with `ims` in `fields`. Each distinct `ims` value then has a cache key of its own. + +That field sits under `modules.application_accelerator` in the cache setting, so varying the cache on `ims` requires [Application Accelerator](/en/documentation/platform/applications/application-accelerator/), while processing an image does not. [Image Processor settings](/en/documentation/platform/applications/image-processor/settings/#cache-variation) maps each of these fields to its control in Azion Console. A cache setting created with that allowlist reads back with this `modules` object: @@ -59,9 +63,9 @@ A cache setting created with that allowlist reads back with this `modules` objec The cache key of a derived image converted to another format also carries the format at the end of the key, with no separator, as in `httpsstatic.example.com/static/images/image_1.jpg@@?ims=880xwebp`. -That key has a cost, and the cost is cardinality. Every distinct `ims` string, in each delivered format, is a distinct stored object. A page that asks for arbitrary widths stores an object per width and format, while a page that asks for four fixed widths stores four per format. So choosing a small set of sizes is a caching decision as much as a layout one. +That key has a cost, and the cost is cardinality. Every distinct `ims` value, in each delivered format, is a separate copy in the cache. A page that asks for arbitrary widths stores a copy per width and format, while a page that asks for four fixed widths stores four per format. So choosing a small set of sizes is a caching decision as much as a layout one. -It is also a billing decision, because the monthly Images meter counts the images that Image Processor processes, not the images that the cache serves. So a derived image that stays in cache is counted when Image Processor builds it, not each time a reader receives it. The cache can remove a little-used object before its maximum age ends, and the next request for that image is processed and counted again. For the rate, refer to [Pricing](/en/documentation/fundamentals/pricing/#image-processor). +The cache also decides how often an image counts as processed. Image Processor processes an image when it builds it, not each time the cache serves it, so a derived image that stays in cache is processed once. The cache can remove a little-used copy before its maximum age ends, and the next request for that image is processed again. For the metric and its rate, refer to [Pricing](/en/documentation/fundamentals/pricing/#image-processor). --- @@ -69,7 +73,7 @@ It is also a billing decision, because the monthly Images meter counts the image Image Processor reads a source image from the origin and returns a derived one without saving it as an asset of the account. You cannot upload images to Image Processor: the source image stays wherever it already lives, and the cache holds the derived images. A workflow that needs to keep a transformed file has to save the response itself. -What the `ims` string can express, and the size of the image, bound the transformation. The operations the string accepts are on [Image Processor URL parameters](/en/documentation/platform/applications/image-processor/url-parameters/), and the maximum size and dimensions are on [Applications limits](/en/documentation/platform/applications/limits/#image-processor). +What `ims` can express, and the size of the image, bound the transformation. The operations `ims` accepts are on [Image Processor URL parameters](/en/documentation/platform/applications/image-processor/url-parameters/), and the maximum size and dimensions are on [Applications limits](/en/documentation/platform/applications/limits/#image-processor). One boundary is worth naming, because two surfaces share a name. [WASM Image Processor](/en/documentation/devtools/azion-lib/wasm-image-processor/) is a WebAssembly library that processes images inside a [Function](/en/documentation/platform/functions/). It runs in the code of that Function, separately from the Image Processor Platform Resource and everything this page describes. @@ -80,8 +84,8 @@ One boundary is worth naming, because two surfaces share a name. [WASM Image Pro The headers and behaviors of Image Processor, including the response headers of a processed image. - Every operation the ims query string expresses, with the values each one accepts. + Every operation the ims parameter expresses, with the values each one accepts. The rule that sends image requests to Image Processor, step by step. - The query-string control that gives each ims string a cache key of its own. + The query-string control that gives each ims value a cache key of its own. diff --git a/apps/docs/src/content/docs/en/pages/build/image-processor/overview.mdx b/apps/docs/src/content/docs/en/pages/build/image-processor/overview.mdx index 97bdf93314..3e6cd5c1f7 100644 --- a/apps/docs/src/content/docs/en/pages/build/image-processor/overview.mdx +++ b/apps/docs/src/content/docs/en/pages/build/image-processor/overview.mdx @@ -10,18 +10,16 @@ import DocButton from '~/components/webkit/DocButton.vue' import DocCardGroup from '@aziontech/webkit/doc-card-group' import DocCard from '@aziontech/webkit/doc-card' -**Image Processor** is a Platform Resource that builds a new image, the derived image, from an image on the origin of an [Application](/en/documentation/platform/applications/). On-request image transformation is a delivery model where the server builds each variant of an image at the time of the request. The URL of the request describes the variant, such as a width, a crop, a quality, or a format. Each variant comes from the one original, so the original is the only file you store and update. - -In an Application, Image Processor reads the source image, the file on the origin, without changing it. The `ims` query string of the request describes the derived image, such as `?ims=fit-in/400x400`. Even with no `ims` query string, Image Processor can convert an image to a format the browser accepts. Image Processor processes only the requests that a Request Phase rule with the _Optimize Images_ behavior matches, and you write that rule in the Application's [Rules Engine](/en/documentation/platform/applications/rules-engine/). Use Image Processor to deliver one image in several sizes, crops, qualities, or formats, such as WEBP for browsers that accept it, without a file per variant. +**Image Processor** is a Platform Resource that builds derived images from origin images on Azion's distributed infrastructure, for the requests received by an [Application](/en/documentation/platform/applications/). On-request image transformation is a delivery model where the server builds each variant of an image at request time, as described in the request URL. Use Image Processor to serve an image in several sizes, crops, qualities, or formats, such as WEBP for browsers that accept it, from one file. - + --- ## Request path -An `ims` query string does not transform an image by itself: a rule with the [Optimize Images](/en/documentation/platform/applications/rules-engine/#optimize-images) behavior has to match the request first. Turning Image Processor on in an Application only makes that behavior available to its rules. +The `ims` query-string parameter does not transform an image by itself: a rule with the [Optimize Images](/en/documentation/platform/applications/rules-engine/#optimize-images) behavior has to match the request first. Turning Image Processor on in an Application only makes that behavior available to its [Rules Engine](/en/documentation/platform/applications/rules-engine/) rules. Solid arrows carry the request, and dotted arrows carry the response. Each label starts with the number of its step below. @@ -34,7 +32,7 @@ flowchart TD IP["Image Processor"] Origin[["origin server"]] Client -->|"1. request for an image"| App - App -.->|"2. no match: unprocessed image"| Client + App -.->|"2. no match: served unprocessed"| Client App -->|"3. cache setting"| Cache Cache -.->|"4. cached derived image"| App App -->|"5. no cached copy"| IP @@ -44,74 +42,25 @@ flowchart TD App -.->|"4, 5. derived image"| Client ``` -1. A request for a path that holds an image reaches the Application, which runs its Request Phase rules. A rule for images matches on `${uri}`, or on `${request_uri}` with [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) on, against an argument such as `\.(jpg|jpeg|gif|bmp|png|ico|webp|avif)`. -2. When no rule with _Optimize Images_ matches, the source image is delivered unprocessed, even when the request carries `ims`. -3. A matching rule applies its behaviors. _Optimize Images_ marks the request for Image Processor. When the rule also carries _Set Cache Policy_, that behavior applies the [cache setting](/en/documentation/platform/applications/cache/cache-settings/) that holds the derived image. A rule can carry _Optimize Images_ alone, because the behavior takes no argument. +1. A request for a path that holds an image reaches the Application, which runs its Request Phase rules, such as a rule with _Optimize Images_ that matches image requests. To build that rule step by step, refer to [Configure Image Processor on an application](/en/documentation/guides/application-performance/delivery-optimization/process-images/). +2. When no rule with _Optimize Images_ matches, the source image, the file on the origin, is delivered unprocessed. +3. A matching rule applies its behaviors. _Optimize Images_ applies Image Processor to the request. When the rule also carries _Set Cache Policy_, that behavior applies the [cache setting](/en/documentation/platform/applications/cache/cache-settings/) that holds the derived image. A rule can carry _Optimize Images_ alone, because the behavior takes no argument. 4. When the derived image is already cached, [Cache](/en/documentation/platform/applications/cache/) delivers it without processing. -5. Otherwise, Image Processor reads the source image from the origin and applies the `ims` query string to it. The derived image is delivered. The Application's cache stores it only when the rule applies a cache setting with _Set Cache Policy_. Without one, every request reaches Image Processor, which answers a repeated transformation from its own cache. - -When a rule with _Optimize Images_ matches a path that does not return an image, the request fails with an empty `400`, so the rule's criteria have to match image paths only. To build that rule step by step, refer to [Configure Image Processor on an application](/en/documentation/guides/application-performance/delivery-optimization/process-images/). +5. Otherwise, Image Processor reads the source image without changing it, and applies `ims` to it, such as `?ims=fit-in/400x400`. The derived image is delivered. The Application's cache stores it only when the rule applies a cache setting with _Set Cache Policy_. Without one, every request reaches Image Processor, which answers a repeated transformation from its own cache. For how the delivered format is chosen, how the cache tells derived images apart, and where Image Processor stops, refer to [Image delivery](/en/documentation/platform/applications/image-processor/image-delivery/). --- -## Rule structure - -Image Processor acts through a Request Phase rule that carries the _Optimize Images_ behavior. To process every request for an image path and cache each derived image, send this rule as the body of `POST /v4/workspace/applications//request_rules`: - -```json -{ - "name": "Optimize images", - "description": "Apply the cache setting and optimize images", - "active": true, - "criteria": [ - [ - { - "conditional": "if", - "variable": "${request_uri}", - "operator": "matches", - "argument": "\\.(jpg|jpeg|gif|bmp|png|ico|webp|avif)" - } - ] - ], - "behaviors": [ - { "type": "set_cache_policy", "attributes": { "value": } }, - { "type": "optimize_images" } - ] -} -``` - -- `criteria` compares the path with a list of image extensions through `matches`. `${request_uri}` needs Application Accelerator, and `${uri}` matches the same paths without it. -- `optimize_images` takes no attributes and marks the request for Image Processor. It requires Image Processor on the Application that runs the rule. -- `set_cache_policy` applies the cache setting whose ID is in `attributes.value`, and that cache setting stores each derived image. With `ims` in the `fields` of its `cache_vary_by_querystring` allowlist, each distinct `ims` string gets a cache key of its own. That field belongs to Application Accelerator, so it needs Application Accelerator on. -- Each request then carries its transformation in the URL, such as `?ims=400x`. A processed response carries `x-ims: Enabled`, and `x-original-image-size` carries the size of the source image before the transformation. - ---- - -## Scope and limits - -- **Application**: Image Processor is off in a new Application, and each Application turns it on separately, in its `modules.image_processor.enabled` field in the API. Even when it is on, Image Processor processes only the requests that a rule with _Optimize Images_ matches. [Main Settings](/en/documentation/platform/applications/main-settings/#platform-resources) shows where to turn it on in Azion Console and the API. -- **Operations**: one `ims` string can carry a resize, a crop, and a chain of filters. The operations are resize, crop, rotation, quality, watermark, format conversion, and fill, and `fit-in` fits an image inside an area without enlarging it. For the syntax and the values each one accepts, refer to [URL parameters](/en/documentation/platform/applications/image-processor/url-parameters/). -- **Parameter position**: `ims` can sit anywhere in the query string. An `ims` value that Image Processor cannot parse returns the source image untransformed. -- **Formats**: Image Processor reads JPEG, GIF, PNG, BMP, ICO, WEBP, and AVIF. Even with no `ims` parameter, it can convert an image to a format the browser accepts, such as WEBP or AVIF, and it converts a BMP image to JPEG or WEBP. A `filters:format()` filter returns the format it names, whatever `Accept` header the request carries. For how the delivered format is chosen, refer to [Image delivery](/en/documentation/platform/applications/image-processor/image-delivery/#format-negotiation). -- **Cache**: once `ims` is in the allowlist of the cache setting, each distinct `ims` string, in each delivered format, is a separate stored object. A page that asks for four fixed widths stores four objects per delivered format, while a page that asks for arbitrary widths stores one per width and format. Once a derived image is in cache, it is delivered without processing. For the practices, refer to [Applications best practices](/en/documentation/platform/applications/best-practices/#image-processor). -- **Storage**: Image Processor returns each derived image without saving it as an asset of the account, and you cannot upload images to Image Processor. The cache holds the derived images, and the source image stays where it already lives. A workflow that needs to keep a transformed file saves the response itself. -- **Neighbors**: [WASM Image Processor](/en/documentation/devtools/azion-lib/wasm-image-processor/) is a WebAssembly library that processes images inside a [Function](/en/documentation/platform/functions/). It runs in the code of that Function, separately from the Image Processor Platform Resource and its settings. -- **Interfaces**: you turn on Image Processor on the **Main Settings** tab of an Application in [Azion Console](https://console.azion.com/), and through [Azion API](https://api.azion.com/) at `/v4/workspace/applications/`. [Azion CLI](/en/documentation/devtools/cli/) sets it with `--image-processor` on `azion create application` or `azion update application`. [`azion.config.js`](/en/documentation/devtools/cli/azion-config-js/) and [Azion Lib](/en/documentation/devtools/azion-lib/) set it with `imageProcessorEnabled`. For each field, flag, behavior, and header, refer to [Image Processor settings](/en/documentation/platform/applications/image-processor/settings/). -- **Observability**: in Azion Console, [Real-Time Metrics](/en/documentation/platform/real-time-metrics/) has an **Image Processor** tab with request charts, and [Real-Time Events](/en/documentation/platform/real-time-events/) has an **Image Processor** dataset, which requires Image Processor on. -- **Limits**: one image takes up to 150 MB, 3840 pixels of width, and 2160 pixels of height. For every bound, refer to [Applications limits](/en/documentation/platform/applications/limits/#image-processor), and for the rates, refer to [Pricing](/en/documentation/fundamentals/pricing/#image-processor). [Azion pricing](https://www.azion.com/en/pricing/) lists what each plan includes. -- **Terms**: the [Applications glossary](/en/documentation/platform/applications/glossary/) defines the words the Image Processor pages give a specific meaning, such as derived image, source image, autocrop, and `fit-in`. - ---- - ## Next steps - + + - + + diff --git a/apps/docs/src/content/docs/en/pages/build/image-processor/quickstart.mdx b/apps/docs/src/content/docs/en/pages/build/image-processor/quickstart.mdx index c4157b00ef..0ee711a273 100644 --- a/apps/docs/src/content/docs/en/pages/build/image-processor/quickstart.mdx +++ b/apps/docs/src/content/docs/en/pages/build/image-processor/quickstart.mdx @@ -15,14 +15,21 @@ import DocStep from '@aziontech/webkit/doc-step' import Tabs from '~/components/webkit/Tabs.vue' import Code from '~/components/webkit/CodeBlock.vue' -This guide instructs you through requesting your first derived image from an Application. By the end you will have: +This guide instructs you through requesting your first derived image, the image that Image Processor builds from a file on your origin. By the end you will have: - [Image Processor](/en/documentation/platform/applications/image-processor/) turned on for one Application. -- A cache setting that stores each transformation as its own object. +- A cache setting that stores each transformation as a separate copy. - A [Rules Engine](/en/documentation/platform/applications/rules-engine/) rule that sends image requests to Image Processor. - A resized image returned from a URL you wrote. -Three entities and one URL carry that result, in this order. The **Application** has Image Processor turned on. The **cache setting** belongs to the Application and makes the cache store two different transformations as two different objects. The **rule** belongs to the Application, matches image requests, and applies both the cache setting and the _Optimize Images_ behavior. The image URL then carries the transformation in its `ims` query string. A request that no rule matches is delivered unprocessed, so the rule is what makes the query string mean anything. +Three entities and one URL carry that result, in this order: + +1. The **Application** has Image Processor turned on. +2. The **cache setting** belongs to the Application and makes the cache store two different transformations as two separate copies. +3. The **rule** belongs to the Application, matches image requests, and applies both the cache setting and the _Optimize Images_ behavior. +4. The image URL carries the transformation in its `ims` query-string parameter. + +A request that no rule matches is delivered unprocessed, so the rule is what makes `ims` mean anything. --- @@ -72,9 +79,9 @@ Three entities and one URL carry that result, in this order. The **Application** ## Turn on Image Processor and Application Accelerator -Image Processor is a Platform Resource that is off in a new Application. This stage turns on two Platform Resources. +Image Processor, the Platform Resource that builds derived images on request, is off in a new Application. This stage turns it on, together with a second Platform Resource. -[Application Accelerator](/en/documentation/platform/applications/application-accelerator/) is the second for two reasons. The field that varies the cache by a query string belongs to it, and the cache setting uses that field. The rule in this guide also reads `${request_uri}`, and Azion refuses a rule that reads it while Application Accelerator is off. Processing an image does not require Application Accelerator, but caching each transformation separately does. +This stage also turns on [Application Accelerator](/en/documentation/platform/applications/application-accelerator/), for two reasons. The field that varies the cache by a query string belongs to it, and the cache setting uses that field. The rule in this guide also reads `${request_uri}`, and Azion refuses a rule that reads it while Application Accelerator is off. Processing an image does not require Application Accelerator, but caching each transformation separately does. @@ -87,7 +94,7 @@ To turn on both Platform Resources in Azion Console: - Access [Azion Console](https://console.azion.com/) > **Applications** > **your Application**. + Access [Azion Console](https://console.azion.com/) > **Applications** > your Application. @@ -179,9 +186,13 @@ The Application now has both Platform Resources turned on, and the _Optimize Ima +:::caution +Turning on Application Accelerator can generate usage-related costs. For more information, refer to [Pricing](/en/documentation/fundamentals/pricing/#application-accelerator). +::: + --- -## Create a cache setting that varies on the ims query string +## Create a cache setting that varies on the ims parameter Without this step, the cache cannot tell one transformation from another. It may answer a request for a 400-pixel image with a 200-pixel one. @@ -196,7 +207,7 @@ To create the cache setting in Azion Console: - Access [Azion Console](https://console.azion.com/) > **Applications** > **your Application**. + Access [Azion Console](https://console.azion.com/) > **Applications** > your Application. @@ -216,7 +227,7 @@ To create the cache setting in Azion Console: In the **Cache** section, in **Max Age**, enter `31536000`. - + The panel is in the **Application Accelerator** section. @@ -231,7 +242,7 @@ To create the cache setting in Azion Console: -The Application now has a cache setting that stores one object per distinct `ims` value. +The Application now has a cache setting that stores a separate copy for each distinct `ims` value. @@ -239,7 +250,7 @@ The Application now has a cache setting that stores one object per distinct `ims ### CLI -The Azion CLI command sends the whole body from a file, because no create flag sets the cache `max_age` or `sort_enabled`. +No create flag sets the cache `max_age` or `sort_enabled`, so the command sends the whole body from a file. To create the cache setting with the Azion CLI: @@ -279,14 +290,16 @@ The Azion CLI command sends the whole body from a file, because no create flag s - --cache-setting-id 123464 --format json`} /> + Replace `` with the id that the create command printed: + + --cache-setting-id --format json`} /> The output reports the `ims` allowlist and the maximum age the file set. -The Application now has a cache setting that stores one object per distinct `ims` value. Record the id the command printed, because the rule applies it. For every flag the command accepts, refer to [Azion CLI cache-setting](/en/documentation/devtools/cli/resources/cache-setting/). +The Application now has a cache setting that stores a separate copy for each distinct `ims` value. Record the id the command printed, because the rule applies it. For every flag the command accepts, refer to [Azion CLI cache-setting](/en/documentation/devtools/cli/resources/cache-setting/). @@ -294,7 +307,7 @@ The Application now has a cache setting that stores one object per distinct `ims ### API -One request carries the cache behavior and the query string allowlist together. +One request carries the cache behavior and the query string allowlist together. To create the cache setting with the Azion API: @@ -333,7 +346,7 @@ One request carries the cache behavior and the query string allowlist together. -The Application now has a cache setting that stores one object per distinct `ims` value. +The Application now has a cache setting that stores a separate copy for each distinct `ims` value. @@ -345,7 +358,7 @@ For the rest of the fields a cache setting carries, including how long an object ## Create a rule that sends image requests to Image Processor -The rule is what turns the query string into a transformation. It matches requests for image paths, applies the cache setting you created, and carries the _Optimize Images_ behavior. +The rule is what turns `ims` into a transformation. It matches requests for image paths, applies the cache setting you created, and carries the _Optimize Images_ behavior. @@ -358,7 +371,7 @@ To create the rule in Azion Console: - Access [Azion Console](https://console.azion.com/) > **Applications** > **your Application**. + Access [Azion Console](https://console.azion.com/) > **Applications** > your Application. @@ -382,7 +395,12 @@ To create the rule in Azion Console: - In the behaviors, select **Set Cache Policy**, then choose the `images` cache setting. + In the behaviors, select _Set Cache Policy_. + + + + + As the cache setting of _Set Cache Policy_, select `images`. @@ -398,12 +416,12 @@ Every request for a path with one of those extensions now gets the `images` cach ### CLI -The criteria carry `${request_uri}`, which a shell expands, and the argument carries backslashes, so the rule goes in a file. +The criteria carry `${request_uri}`, which a shell expands, and the argument carries backslashes, so the rule goes in a file. To create the rule with the Azion CLI: - Save the following as `rule.json`, with the id of your cache setting in the `set_cache_policy` behavior: + Save the following as `rule.json`, and replace `` with the id of your cache setting: } }, { "type": "optimize_images" } ] }`} /> @@ -449,12 +467,12 @@ Every request for a path with one of those extensions now gets the `images` cach ### API -The criteria carry `${request_uri}`, which a shell expands, and the argument carries backslashes, so the body is sent from a file. +The criteria carry `${request_uri}`, which a shell expands, and the argument carries backslashes, so the body is sent from a file. To create the rule with the Azion API: - Save the following as `rule.json`, with the id of your cache setting in the `set_cache_policy` behavior: + Save the following as `rule.json`, and replace `` with the `data.id` that the cache setting create returned: } }, { "type": "optimize_images" } ] }`} /> @@ -503,7 +521,7 @@ Every request for a path with one of those extensions now gets the `images` cach :::note -This part is optional. An **Add Request Header** behavior with `Accept: image/webp` on the same rule makes the automatic conversion deliver WEBP to every request the rule matches, including one whose browser asked for PNG. Add it only when every client of those paths displays WEBP. In the Azion CLI and the API, it is a behavior of type `add_request_header`, whose `attributes` carry `"value": "Accept: image/webp"`. For the behavior's fields, refer to [Image Processor settings](/en/documentation/platform/applications/image-processor/settings/). +An optional _Add Request Header_ behavior with `Accept: image/webp` on the same rule makes the automatic conversion deliver WEBP to every request the rule matches, including one whose browser asked for PNG. Add it only when every client of those paths displays WEBP. In the Azion CLI and the API, it is a behavior of type `add_request_header`, whose `attributes` carry `"value": "Accept: image/webp"`. For the behavior's fields, refer to [Image Processor settings](/en/documentation/platform/applications/image-processor/settings/). ::: --- @@ -512,7 +530,7 @@ This part is optional. An **Add Request Header** behavior with `Accept: image/we Ask for a width and see the response change. -Request one of your images with an `ims` query string, replacing the host and the path with your own: +Request one of your images with an `ims` parameter in its query string, replacing the host and the path with your own: - + diff --git a/apps/docs/src/content/docs/en/pages/build/image-processor/settings.mdx b/apps/docs/src/content/docs/en/pages/build/image-processor/settings.mdx index ba714d6191..99d41d3239 100644 --- a/apps/docs/src/content/docs/en/pages/build/image-processor/settings.mdx +++ b/apps/docs/src/content/docs/en/pages/build/image-processor/settings.mdx @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -[Image Processor](/en/documentation/platform/applications/image-processor/) is a Platform Resource that builds a derived image from the source image on the origin of an [Application](/en/documentation/platform/applications/). It is off in a new Application, and each Application turns it on separately. With Image Processor on, a request for an image can carry an `ims` query string that describes a transformation. This page carries the field, the flag, and the interface that sets each one, plus the behaviors, cache fields, headers, and datasets that Image Processor reaches. +[Image Processor](/en/documentation/platform/applications/image-processor/) is a Platform Resource that builds a derived image from the source image on the origin of an [Application](/en/documentation/platform/applications/). It is off in a new Application, and each Application turns it on separately. With Image Processor on, a request for an image can carry an `ims` query-string parameter that describes a transformation. --- @@ -22,13 +22,13 @@ Five interfaces set the same switch, and the switch belongs to the Application: | Interface | Where you set it | Field or flag | | --- | --- | --- | -| Azion Console | The **Default Modules** group of the **Modules** section, on the **Main Settings** tab of an Application | The **Image Processor** toggle, with the helper text "Enable dynamic image editing options." | +| Azion Console | **Main Settings** tab › **Modules** › **Default Modules** of an Application | The **Image Processor** toggle | | Azion API v4 | `PATCH /v4/workspace/applications/` | `modules.image_processor.enabled` | | Azion API v3 | `PATCH https://api.azionapi.net/edge_applications/` | `image_optimization` | | [Azion CLI](/en/documentation/devtools/cli/) | `azion create application` and `azion update application` | `--image-processor` | | [`azion.config.js`](/en/documentation/devtools/cli/azion-config-js/) and [Azion Lib](/en/documentation/devtools/azion-lib/) | An entry of `applications`, one per Application | `imageProcessorEnabled` | -`modules.image_processor.enabled` and `imageProcessorEnabled` are booleans, and both default to `false`. The Azion CLI flag takes a string: `--image-processor true`. In Azion Console, the toggle is saved with **Save**. +`modules.image_processor.enabled` and `imageProcessorEnabled` are booleans, and both default to `false`. The Azion CLI flag takes a string: `--image-processor true`. In Azion Console, the toggle carries the helper text "Enable dynamic image editing options." and is saved with **Save**. API v4 carries the switch in the `modules` object of the Application: @@ -48,23 +48,49 @@ The same `modules` object carries `application_accelerator`, `cache`, and `funct ## Rules Engine behaviors -A rule for images can carry three [Rules Engine](/en/documentation/platform/applications/rules-engine/) behaviors. Only **Optimize Images** is needed to process an image, and it requires Image Processor on the Application that runs the rule. +A rule for images can carry three [Rules Engine](/en/documentation/platform/applications/rules-engine/) behaviors. Only _Optimize Images_ is needed to process an image, and it requires Image Processor on the Application that runs the rule. | Behavior | Phase | API type | What it does | | --- | --- | --- | --- | -| **Optimize Images** | **Request Phase** | `optimize_images` | Applies Image Processor to the matched request. It takes no attributes. | -| **Set Cache Policy** | **Request Phase** | `set_cache_policy` | Applies a cache setting to the matched request. | -| **Add Request Header** | **Request Phase** | `add_request_header` | Adds a header to the request. | +| _Optimize Images_ | **Request Phase** | `optimize_images` | Applies Image Processor to the matched request. It takes no attributes. | +| _Set Cache Policy_ | **Request Phase** | `set_cache_policy` | Applies a cache setting to the matched request. | +| _Add Request Header_ | **Request Phase** | `add_request_header` | Adds a header to the request. | -For **Set Cache Policy**, `attributes.value` carries the id of the cache setting, and in Azion Console you select it in a second dropdown. For **Add Request Header**, `attributes.value` takes the form `Field: value`, such as `Accept: image/webp` or `Accept: image/avif`. +For _Set Cache Policy_, `attributes.value` carries the id of the cache setting, and in Azion Console you select it in a second dropdown. For _Add Request Header_, `attributes.value` takes the form `Field: value`, such as `Accept: image/webp` or `Accept: image/avif`. A criterion of the same rule carries `variable`, `operator`, `conditional`, and `argument`. A rule that matches image requests reads `${request_uri}` or `${uri}` with the `matches` operator, against an argument such as `\.(jpg|jpeg|gif|bmp|png|ico|webp|avif)`. `${request_uri}` requires Application Accelerator on the Application: while Application Accelerator is off, the API refuses a rule that reads it and returns the error `25047`. `${uri}` depends on no Platform Resource. +To process every request for an image path and cache each derived image, send this rule as the body of `POST /v4/workspace/applications/{application_id}/request_rules`: + +```json +{ + "name": "Optimize images", + "description": "Apply the cache setting and optimize images", + "active": true, + "criteria": [ + [ + { + "conditional": "if", + "variable": "${request_uri}", + "operator": "matches", + "argument": "\\.(jpg|jpeg|gif|bmp|png|ico|webp|avif)" + } + ] + ], + "behaviors": [ + { "type": "set_cache_policy", "attributes": { "value": } }, + { "type": "optimize_images" } + ] +} +``` + +Replace `` with the id of the cache setting that stores the derived images. + --- ## Cache variation -A derived image is cached under a key of its own when its cache setting varies the cache on `ims`, because the cache key then includes the `ims` query string after `@@`. A variation with a converted format also carries the file format at the end of the key, with no separator, as in `httpsstatic.example.com/static/images/image_1.jpg@@?ims=880xwebp`. +A derived image gets a cache key of its own when its cache setting varies the cache on `ims`. The key then carries the `ims` value after `@@`, and a copy with a converted format also carries the file format at the end of the key, with no separator, as in `httpsstatic.example.com/static/images/image_1.jpg@@?ims=880xwebp`. Varying the cache on a query string uses an [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) field: `cache_vary_by_querystring`, under `modules.application_accelerator` in a cache setting. So varying the cache on `ims` requires Application Accelerator, while processing an image does not. @@ -72,9 +98,9 @@ In Azion Console, each field maps to a control of the **Cache vary by Query Stri | Field | Console control | What it sets | | --- | --- | --- | -| `cache_vary_by_querystring.behavior` | **Behavior** | How the cache handles query string parameters. The dropdown offers _Allowlist_, _Denylist_, _Ignore_, and _All_. | -| `cache_vary_by_querystring.fields` | **Fields** | The query string parameters considered for cache variation, one per line. | -| `cache_vary_by_querystring.sort_enabled` | **Sort** | Whether query string parameters are sorted, so that cache behavior does not depend on the order they arrive in. | +| `cache_vary_by_querystring.behavior` | **Behavior** | The mode that decides how the query string varies the key: _Allowlist_, _Denylist_, _Ignore_, or _All_. | +| `cache_vary_by_querystring.fields` | **Fields** | The query string arguments the mode applies to, one per line. | +| `cache_vary_by_querystring.sort_enabled` | **Sort** | Whether every order of the arguments groups under one key, sorted alphabetically. | A cache setting for images carries `ims` in `fields`. For the rest of the fields a cache setting carries, including the maximum age of the cached object, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/). For the other fields Application Accelerator unlocks, refer to [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/). @@ -93,11 +119,11 @@ Azion returns two headers on a response that Image Processor processed. ## Usage and event data -Azion reports Image Processor activity on six surfaces: four in Azion Console, two each in Real-Time Metrics and Real-Time Events, and two in GraphQL. +Azion reports Image Processor activity on six surfaces: two each in Real-Time Metrics and Real-Time Events, all in Azion Console, and two in GraphQL. | Surface | What it carries | | --- | --- | -| The **Image Processor** tab of [Real-Time Metrics](/en/documentation/platform/real-time-metrics/) | Metrics for the requests made to the images processed through Image Processor in your account, as Total Requests and Total Requests per Second charts. | +| The **Image Processor** tab of [Real-Time Metrics](/en/documentation/platform/real-time-metrics/) | Total Requests and Total Requests per Second charts for the images Image Processor processed in your account. | | The **Bandwidth Saving** dashboard in the **Applications** tab of Real-Time Metrics | The bytes Image Processor saved on the images it processed and delivered. | | The **Image Processor** dataset of [Real-Time Events](/en/documentation/platform/real-time-events/) | The event records of requests made to Applications that use Image Processor. | | The **Proxy Upstream** field of the Tiered Cache data source of Real-Time Events | `ims_http`, the value the field reads when Image Processor is the upstream of the Tiered Cache layer. | @@ -120,7 +146,7 @@ WASM Image Processor is a WebAssembly library that processes images inside a [Fu Turn Image Processor on and request a transformed image for the first time. How the delivered format is chosen, how a derived image is cached, and where Image Processor stops. - The grammar of the `ims` query string these settings switch on. + The grammar of the `ims` parameter these settings switch on. The steps that turn Image Processor on and build the rule, interface by interface. diff --git a/apps/docs/src/content/docs/en/pages/build/image-processor/url-parameters.mdx b/apps/docs/src/content/docs/en/pages/build/image-processor/url-parameters.mdx index 65df80317b..b12cc95184 100644 --- a/apps/docs/src/content/docs/en/pages/build/image-processor/url-parameters.mdx +++ b/apps/docs/src/content/docs/en/pages/build/image-processor/url-parameters.mdx @@ -1,7 +1,7 @@ --- title: Image Processor URL parameters description: >- - Look up every ims query string operation: resize, crop, rotate, quality, + Look up every operation of the ims parameter: resize, crop, rotate, quality, watermark, format conversion, and fill, with the values each one accepts. meta_tags: 'image processor, ims, query string, resize, crop, rotate, watermark, format conversion, fill' namespace: documentation_products_image_processor_url_parameters @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -The `ims` query string carries the transformation [Image Processor](/en/documentation/platform/applications/image-processor/) applies to an image. One string can hold a resize, a crop, and a chain of filters. Image Processor returns a derived image built from the source image on the origin, and it reads the source image without changing it. This page carries the syntax of each operation, the values its arguments accept, and a rendered result. +The `ims` query-string parameter carries the transformation [Image Processor](/en/documentation/platform/applications/image-processor/) applies to an image. One `ims` value can hold a resize, a crop, and a chain of filters. Image Processor returns a derived image built from the source image on the origin, and it reads the source image without changing it. --- @@ -169,7 +169,7 @@ The image below carries `?ims=fit-in/400x400/filters:fill(gray)`: ## Combined filters -One `ims` string can carry more than one filter. The filters go inside a single `filters:` group, and a `:` separates each one from the next, as in `filters:filter1(arg1):filter2(arg2)`. +One `ims` value can carry more than one filter. The filters go inside a single `filters:` group, and a `:` separates each one from the next, as in `filters:filter1(arg1):filter2(arg2)`. | Segment | Example | What it does | | --- | --- | --- | @@ -199,7 +199,7 @@ Image Processor accepts these source image formats: A browser displays a WEBP or AVIF derived image only when it supports that format. For the browsers that support each one, refer to [WEBP browser support](https://caniuse.com/webp) and [AVIF browser support](https://caniuse.com/avif). -Image Processor also converts a format with no `ims` parameter in the request. It detects which formats the browser supports and, when possible, converts the image to one of them, such as WEBP or AVIF. BMP images are converted to JPEG or WEBP depending on the same browser support. For more information, refer to [Image delivery](/en/documentation/platform/applications/image-processor/image-delivery/). +Image Processor can also convert an image with no `ims` parameter in the request, to a format the browser supports, as [Format negotiation](/en/documentation/platform/applications/image-processor/image-delivery/#format-negotiation) explains. --- diff --git a/apps/docs/src/content/docs/en/pages/hubs/guides/applications.mdx b/apps/docs/src/content/docs/en/pages/hubs/guides/applications.mdx index 986a067757..7c70932769 100644 --- a/apps/docs/src/content/docs/en/pages/hubs/guides/applications.mdx +++ b/apps/docs/src/content/docs/en/pages/hubs/guides/applications.mdx @@ -1,10 +1,10 @@ --- title: Applications guides and tutorials -description: Every guide and tutorial for Applications and the Platform Resources nested in it. +description: Find every guide and tutorial for Applications and the Platform Resources nested in it. meta_tags: 'applications, guides, tutorials' namespace: documentation_products_applications_guides permalink: /documentation/platform/applications/guides/ guides_hub: applications --- -Each guide opens in the Guides section, where every guide lives. +This hub lists every guide and tutorial for Applications and for Cache, Application Accelerator, and Image Processor, and each one opens in the Guides section. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/cache-settings.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/cache-settings.mdx index 9679b193fe..b265c84f59 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/cache-settings.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/cache-settings.mdx @@ -12,7 +12,9 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -A cache setting is a set of values that tell [Cache](/en/documentation/platform/applications/cache/) how to store and serve a response. It belongs to one Application. Its values are the browser time to live (TTL), the cache TTL and behavior, stale cache, Large File Optimization, [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/), and the cache variations. A [Rules Engine](/en/documentation/platform/applications/rules-engine/) rule with the [Set Cache Policy](/en/documentation/platform/applications/rules-engine/#set-cache-policy) behavior applies the setting, and the setting acts only on the requests that this rule matches. To create one, refer to [Create a cache setting](/en/documentation/guides/application-performance/cache-and-purge/tune-cache-settings/). +A cache setting is a set of values that tell [Cache](/en/documentation/platform/applications/cache/) how to store and serve a response. It belongs to one Application. Its values are the browser time to live (TTL), the cache TTL and behavior, stale cache, Large File Optimization, [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/), and the cache variations. + +A [Rules Engine](/en/documentation/platform/applications/rules-engine/) rule with the [Set Cache Policy](/en/documentation/platform/applications/rules-engine/#set-cache-policy) behavior applies the setting, and the setting acts only on the requests that this rule matches. To create one, refer to [Create a cache setting](/en/documentation/guides/application-performance/cache-and-purge/tune-cache-settings/). --- @@ -25,7 +27,7 @@ Six interfaces create and change the same cache setting. The tables on this page | [Azion Console](https://console.azion.com/) | The **Cache Settings** tab of an Application in [Applications](/en/documentation/platform/applications/), then **+ Cache**, which opens the **Create Cache Settings** drawer | The same tab lists every setting with its **Name**, **Browser Cache**, and **Cache** | | [Azion API v4](/en/documentation/devtools/api/) | `POST /v4/workspace/applications/{application_id}/cache_settings` | `GET`, `PUT`, `PATCH`, and `DELETE /v4/workspace/applications/{application_id}/cache_settings/{cache_setting_id}`; `GET /v4/workspace/applications/{application_id}/cache_settings` lists them | | Azion CLI | [`azion create cache-setting`](/en/documentation/devtools/cli/resources/cache-setting/) | [`azion describe cache-setting`](/en/documentation/devtools/cli/resources/cache-setting/), [`azion list cache-setting`](/en/documentation/devtools/cli/resources/cache-setting/), [`azion update cache-setting`](/en/documentation/devtools/cli/resources/cache-setting/), [`azion delete cache-setting`](/en/documentation/devtools/cli/resources/cache-setting/) | -| `azion.config.js` | An entry of the `cache` array of an Application, of type `AzionCache` | The same entry | +| [`azion.config.js`](/en/documentation/devtools/cli/azion-config-js/) | An entry of the `cache` array of an Application, of type `AzionCache` | The same entry | | [Azion Lib](/en/documentation/devtools/azion-lib/application/) | `createCacheSetting` from `azion/applications` | `getCacheSetting`, `getCacheSettings`, `updateCacheSetting`, and `deleteCacheSetting` from `azion/applications` | | [Terraform](/en/documentation/devtools/terraform/applications/) | The `azion_application_cache_setting` resource, whose page documents `application_id` and `name` | The same resource | @@ -35,7 +37,7 @@ In `azion.config.js`, an `AzionCache` entry carries `name`, `stale`, `queryStrin --- -## General +## Name In Azion Console, the **General** section of the **Create Cache Settings** drawer holds the name. `name` is the only field the API requires. @@ -54,7 +56,7 @@ The `browser_cache` object sets what the browser is told to keep. In Azion Conso | **Browser Cache** radios | `browser_cache.behavior` | enum | _Honor cache policies_ (`honor`), _Override cache settings_ (`override`), _No cache_ (`no-cache`) | `honor` | `--browser-cache-behavior` | | **Max Age** under _Override cache settings_ | `browser_cache.max_age` | integer, seconds | 0 to 31,536,000 | `0` | `--browser-cache-max-age` | -`honor` keeps the `Cache-Control` and `Expires` headers the origin sends and forwards them to the browser. `override` replaces them with the TTL in `browser_cache.max_age`. For `no-cache`, the _No cache_ option of Azion Console reads: "Disable browser caching to ensure content is always fetched directly from the server". On `azion update cache-setting`, the flag for `browser_cache.behavior` is `--browser-cache-settings`. +`honor` keeps the `Cache-Control` and `Expires` headers the origin sends and forwards them to the browser. `override` replaces them with the TTL in `browser_cache.max_age`. `no-cache` turns browser caching off. The _No cache_ option of Azion Console reads: "Disable browser caching to ensure content is always fetched directly from the server". On `azion update cache-setting`, the flag for `browser_cache.behavior` is `--browser-cache-settings`. --- @@ -74,10 +76,16 @@ The `modules.cache` object sets how long Azion keeps a copy of a response and wh `honor` keeps the `Cache-Control` and `Expires` headers the origin sends, and `override` replaces them with the TTL in `modules.cache.max_age`. When the origin sends neither `Cache-Control` nor `Expires`, `honor` keeps the copy for the Max Age of the setting, `modules.cache.max_age`. -Stale cache, the `stale_cache.enabled` field, lets Azion serve an expired copy for a limited window when the origin fails to answer. Large File Optimization, the `large_file_cache.enabled` field, stores a large object in fragments, and `large_file_cache.offset` holds their size, fixed at 1,024 kB. Tiered Cache is a Feature of Cache that adds a second cache layer between the data center that answers a request and your origin. `tiered_cache.enabled` turns it on for the objects this setting caches, and `tiered_cache.topology` selects where that layer holds them. A `tiered_cache` object sent without `enabled` turns the layer on. For how each one behaves on a request, refer to [Expiration and freshness](/en/documentation/platform/applications/cache/expiration-and-freshness/). +Stale cache, turned on in `stale_cache.enabled`, lets Azion serve an expired copy for a limited window when the origin fails to answer. Large File Optimization, turned on in `large_file_cache.enabled`, stores a large object in fragments, and `large_file_cache.offset` holds their size, fixed at 1,024 kB. + +Tiered Cache is a Feature of Cache that adds a second cache layer between the data center that answers a request and your origin. `tiered_cache.enabled` turns it on for the objects this setting caches, and `tiered_cache.topology` selects where that layer holds them. A `tiered_cache` object sent without `enabled` turns the layer on. + +For how each one behaves on a request, refer to [Expiration and freshness](/en/documentation/platform/applications/cache/expiration-and-freshness/). :::note -Two constraints bind these values. A `modules.cache.max_age` below 60 seconds requires [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) on the Application; without it, the API refuses the setting with error `21021`. In Azion Console, the **Max Age** field states a minimum of 3 seconds once **Large file optimization** is on. Without Application Accelerator, the API still refuses a value below 60 seconds with error `21021`. Tiered Cache requires `override` in `modules.cache.behavior`; with `honor`, the API refuses the setting with error `21001`. In Azion Console, turning on **Large file optimization** or **Tiered Cache** disables the _Honor cache policies_ option and selects _Override cache behavior_, but the API accepts `honor` with Large File Optimization. +A `modules.cache.max_age` below 60 seconds requires [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) on the Application, or the API refuses the setting with error `21021`. In Azion Console, the **Max Age** field states a minimum of 3 seconds once **Large file optimization** is on. + +Tiered Cache requires `override` in `modules.cache.behavior`, or the API refuses the setting with error `21001`. In Azion Console, turning on **Large file optimization** or **Tiered Cache** disables the _Honor cache policies_ option and selects _Override cache behavior_, but the API accepts `honor` with Large File Optimization. ::: --- @@ -90,7 +98,7 @@ Together, the fields of `modules.application_accelerator` configure Advanced Cac | Console control | API field | Type | Values | Default | CLI flag | | --- | --- | --- | --- | --- | --- | -| **Cache vary by Method** > **POST**, **OPTIONS** | `cache_vary_by_method` | array of enum, at most 2 values | `post`, `options` | `[]` | On create, `--enable-caching-for-options` and `--file`. On update, `--enable-caching-for-options` and `--enable-caching-for-post` | +| **Cache vary by Method** > **POST**, **OPTIONS** | `cache_vary_by_method` | array of enum, at most 2 values | `post`, `options` | `[]` | Create: `--enable-caching-for-options`, `--file`. Update: also `--enable-caching-for-post` | | **Cache vary by Query String** > **Behavior** | `cache_vary_by_querystring.behavior` | enum | _Ignore_ (`ignore`), _All_ (`all`), _Allowlist_ (`allowlist`), _Denylist_ (`denylist`) | `ignore` | `--cache-by-query-string` | | **Cache vary by Query String** > **Fields** | `cache_vary_by_querystring.fields` | array of string | query string argument names | `[]` | `--query-string-fields` | | **Cache vary by Query String** > **Sort** | `cache_vary_by_querystring.sort_enabled` | boolean | `true`, `false` | `false` | On create, `--file` only. On update, `--enable-caching-string-sort` | @@ -101,13 +109,15 @@ Together, the fields of `modules.application_accelerator` configure Advanced Cac On `azion create cache-setting`, `--enable-caching-for-options` writes `options` whatever its value, and `post` takes `--file`. On `azion update cache-setting`, a call that passes one method flag drops the other method, so pass both flags to keep both. -`ignore` keeps the same key whatever the values are, and `all` varies the key by every value that arrives. `allowlist` varies it by the named values, and `denylist` varies it by every value except the named ones. `fields`, `cookie_names`, and `device_group` hold the named values. `sort_enabled` groups the same arguments under one key whatever order they arrive in. `allowlist` and `denylist` on the query string need at least one field, or the API returns error `21018`. For the steps in Azion Console that set these controls, refer to [Configure Advanced Cache Key for an application](/en/documentation/guides/application-performance/cache-and-purge/advanced-cache-key/). +`ignore` keeps the same key whatever the values are, and `all` varies the key by every value that arrives. `allowlist` varies it by the named values, and `denylist` varies it by every value except the named ones. `fields`, `cookie_names`, and `device_group` hold the named values. + +`sort_enabled` groups the same arguments under one key whatever order they arrive in. `allowlist` and `denylist` on the query string need at least one field, or the API returns error `21018`. For the steps in Azion Console that set these controls, refer to [Configure Advanced Cache Key for an application](/en/documentation/guides/application-performance/cache-and-purge/advanced-cache-key/). --- ## Request body and CLI command -The request body below creates a complete cache setting through `POST /v4/workspace/applications/{application_id}/cache_settings`: +The request body below creates a complete cache setting through `POST /v4/workspace/applications/{application_id}/cache_settings`. It keeps each response for 300 seconds in Azion's cache and for one day in the browser: ```json { @@ -128,20 +138,36 @@ The request body below creates a complete cache setting through `POST /v4/worksp The API answers with HTTP `201`, `state` set to `executed`, and the new cache setting with its `id` under `data`: ```json -{"state":"executed","data":{"id":123456,"name":"static-assets",...,"created_at":"2026-01-01T12:00:00.577248Z"}} +{ + "state": "executed", + "data": { + "id": 123456, + "name": "static-assets", + ..., + "created_at": "2026-01-01T12:00:00.577248Z" + } +} ``` The list endpoint wraps the cache settings of an Application in a page envelope: ```json -{"count":2,"total_pages":1,"page":1,"page_size":10,"next":null,"previous":null,"results":[...]} +{ + "count": 2, + "total_pages": 1, + "page": 1, + "page_size": 10, + "next": null, + "previous": null, + "results": [...] +} ``` The CLI writes the fields its flags cover from the command line: ```bash azion create cache-setting \ - --application-id \ + --application-id \ --name "product-listing" \ --browser-cache-behavior override \ --browser-cache-max-age 30 \ diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/device-groups.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/device-groups.mdx index a4b4cacd8a..25b6a2b7bc 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/device-groups.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/device-groups.mdx @@ -10,7 +10,9 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Device Groups is a Feature of Applications that groups the requests received by an [Application](/en/documentation/platform/applications/) according to the client device. A device group is a name and a regular expression that the Application compares with the `User-Agent` header of each request. A request belongs to the group when its header matches the expression. Device groups require [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) turned on in the Application. A [rule](/en/documentation/platform/applications/rules-engine/) or a [cache setting](/en/documentation/platform/applications/cache/cache-settings/) can then treat those devices apart from the rest. Each Application holds its own device groups, and [Create device groups](/en/documentation/guides/application-development/getting-started/create-device-groups/) shows how to add one in Azion Console. +Device Groups is a Feature of Applications that groups the requests received by an [Application](/en/documentation/platform/applications/) according to the client device. A device group is a name and a regular expression that the Application compares with the `User-Agent` header of each request. A request belongs to the group when its header matches the expression. + +Device groups require [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) turned on in the Application. A [rule](/en/documentation/platform/applications/rules-engine/) or a [cache setting](/en/documentation/platform/applications/cache/cache-settings/) can then treat those devices apart from the rest. Each Application holds its own device groups, and [Create device groups](/en/documentation/guides/application-development/getting-started/create-device-groups/) shows how to add one in Azion Console. --- @@ -25,7 +27,7 @@ A device group carries two fields that you set, and an ID and a creation date th | ID | `id` | integer | Read-only | The identifier of the group | | Creation date | `created_at` | date-time | Read-only | When the group was created | -The cache key of a copy that varies by device ends with the name of the group. The name takes only letters and numbers, with no spaces or symbols, and the API refuses another name with HTTP `400` and error `27003`, `Device Group Invalid Name`. In Azion Console, the **Name** field states `Use only letters and numbers, without spaces or symbols.` The Console shows `Name must be alphanumeric` for a name with other characters. +The cache key of a cached copy of an object that varies by device ends with the name of the group. The name takes only letters and numbers, with no spaces or symbols, and the API refuses another name with HTTP `400` and error `27003`, `Device Group Invalid Name`. In Azion Console, the **Name** field states `Use only letters and numbers, without spaces or symbols.` The Console shows `Name must be alphanumeric` for a name with other characters. The regular expression follows Perl Compatible Regular Expressions (PCRE). Azion Console shows these messages for an expression it refuses: @@ -33,8 +35,6 @@ The regular expression follows Perl Compatible Regular Expressions (PCRE). Azion - `User Agent cannot contain emojis or null bytes` for an expression that carries either. - `User Agent cannot contain < > " or '` for an expression that carries one of those characters. -The `cache_vary_by_devices.device_group` field of a cache setting lists device groups by their ID. - --- ## User-Agent header @@ -67,7 +67,7 @@ An Application compares the regular expression of each device group with the `Us ### Match order -When a `User-Agent` header matches more than one device group, the request takes the first group that matches, from first to last in the list of device groups. The position of the matching words inside the header does not change the result. For example, an Application holds these three device groups, in this order: +When a `User-Agent` header matches more than one device group, the request takes the first match in the list of device groups. The position of the matching words inside the header does not change the result. For example, an Application holds these three device groups, in this order: | Order | Device group | Regular expression | | --- | --- | --- | @@ -101,11 +101,17 @@ For every variable and operator a rule can use, refer to [Rules Engine for Appli ## Cache variation -A cache setting can vary the cache key by device group. With the variation, [Cache](/en/documentation/platform/applications/cache/) stores a separate copy of an object for each device group that the cache setting lists. Otherwise, Cache answers every device with the same copy. In the API, the variation is the `modules.application_accelerator.cache_vary_by_devices` field, whose `device_group` field lists device groups by ID. A cache setting that does not set the variation carries `"behavior": "ignore"` and an empty `device_group` list. [Azion CLI](/en/documentation/devtools/cli/) has no flag for device group variation. +A cache setting can vary the cache key by device group. With the variation, [Cache](/en/documentation/platform/applications/cache/) stores a separate copy of an object for each device group that the cache setting lists. Otherwise, Cache answers every device with the same copy. + +In the API, the variation is the `modules.application_accelerator.cache_vary_by_devices` field, whose `device_group` field lists device groups by ID. A cache setting that does not set the variation carries `"behavior": "ignore"` and an empty `device_group` list. [Azion CLI](/en/documentation/devtools/cli/) has no flag for device group variation. The `modules.application_accelerator` object of a cache setting requires Application Accelerator turned on in the Application. Without it, the API refuses with error `21013` a variation of that object whose `behavior` is not `ignore`. For the values each field takes and its label in Azion Console, refer to [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/#cache-variation). -Each copy that varies by device group has its own cache key. The key ends in `@@` and the name of the device group, such as `httpwww.example.com/@@Mobile`. A URL purge does not reach these copies, so purge them by cache key or with a wildcard. For the key format, refer to [Cache keys](/en/documentation/platform/applications/cache/cache-keys/#variations). For the purge types, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#url-purge). +Each copy that varies by device group has its own cache key. The key ends in `@@` and the name of the device group, such as `httpwww.example.com/@@Mobile`. For the key format, refer to [Cache keys](/en/documentation/platform/applications/cache/cache-keys/#variations). For the purge types, refer to [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/#url-purge). + +:::caution +A URL purge does not reach the copies that vary by device group, so purge them by cache key or with a wildcard. +::: --- @@ -142,6 +148,18 @@ Azion CLI manages device groups with five commands under the `device-group` noun --- +## Errors + +The API refuses a device group, or a cache setting that varies by one, with these errors: + +| Code | Title | Status | What causes it | What to do | +| --- | --- | --- | --- | --- | +| `27002` | `Application Acceleration Not Enabled` | 403 | A new device group, with Application Accelerator off | Turn on Application Accelerator, then create the device group again | +| `27003` | `Device Group Invalid Name` | 400 | A `name` with characters other than letters and numbers | Use only letters and numbers | +| `21013` | `This Configuration Requires The Edge Application's Application Accelerator Module` | 400 | A device group variation in a cache setting, with Application Accelerator off | Turn on Application Accelerator, then save the cache setting again | + +--- + ## Related resources diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/domains/mtls.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/domains/mtls.mdx index 06eb2ae16e..fbadb76cd1 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/domains/mtls.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/domains/mtls.mdx @@ -105,7 +105,7 @@ A Workload checks client certificates only when these conditions hold: - **A Trusted CA certificate exists in Certificate Manager.** A third-party certificate authority issues it, and you upload it before you set `mtls.config.certificate`. A certificate that Azion generates, such as the Azion SAN certificate, cannot serve as the Trusted CA. - **Clients send SNI in `enforce` mode.** Server Name Indication (SNI) is the TLS extension that names the host in the handshake. A connection without SNI reaches the default configuration, which presents the Azion SAN certificate. That certificate is Azion's own, with its hostnames listed as Subject Alternative Names (SAN). On a Workload in `enforce` mode, Azion closes such a connection before it resolves a route of your application. -For the maximum size of a Trusted CA certificate, refer to [Workloads limits](/en/documentation/platform/workloads/limits/). +For the maximum size of a Trusted CA certificate, refer to [Certificate Manager limits](/en/documentation/platform/certificate-manager/limits/). --- @@ -147,6 +147,6 @@ The Workload requests a certificate, the client sends none, and the connection e The Trusted CA certificates a Workload uses in mTLS, the CRLs it lists, and how to upload each one. The steps that upload a Trusted CA, turn on mTLS on a Workload, and add a permissive rule. Every other field of a Workload, from domains and ports to the server certificate in TLS. - The bound on the size of a Trusted CA certificate. + The bound on the size of a Trusted CA certificate. diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/edge-application.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/edge-application.mdx index 006b0574c2..0d7045a331 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/edge-application.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/edge-application.mdx @@ -13,20 +13,28 @@ import VersionRollingOut from '~/includes/snippets/versionRollingOut/en/snippet. [Applications | v3](/en/documentation/platform/applications/v3/) -**Applications** is a Platform Resource that processes the requests received by your [Workloads](/en/documentation/platform/workloads/). An Application can run serverless functions, act as a reverse proxy for your origins, or combine the two, on Azion's distributed infrastructure, from the data center nearest to your user. A serverless function is a [Function](/en/documentation/platform/functions/), code run on demand at each request, with no server for you to provision. A reverse proxy is a server in front of your origin, the server that holds your content. The proxy can answer each request with a cached copy of an earlier origin response, add or remove headers, or route the request to your origin. Every request passes through the proxy, so your clients reach a single domain, and the proxy applies the logic that each origin would otherwise repeat. +**Applications** is a Platform Resource that processes the requests received by your [Workloads](/en/documentation/platform/workloads/), from the data center nearest to your user. An Application can run serverless functions, act as a reverse proxy for your origins, or combine the two. It can also store responses with [Cache](/en/documentation/platform/applications/cache/), unlock four capabilities for the cache and the rules with [Application Accelerator](/en/documentation/platform/applications/application-accelerator/), and transform images with [Image Processor](/en/documentation/platform/applications/image-processor/). Use Applications to run a [Function](/en/documentation/platform/functions/), set the [Connector](/en/documentation/platform/connectors/) that reaches each origin, add or remove headers, or rewrite requests. -An Application receives the requests of a Workload once that Workload's deployment sets that Application. On each request, the Application runs its rules. A rule can set the [Connector](/en/documentation/platform/connectors/) that routes the request to your origin, decide whether the response is cached, or run a Function. Use Applications to route each path to its origin, cache responses, add or remove headers, rewrite requests, run your own code on the requests a rule matches, or resize and convert images on demand. +Each Application can use these nested resources and features: + +- [Cache](/en/documentation/platform/applications/cache/) lets an Application answer a request with a copy of an earlier origin response. For example, your static files stay in the data center nearest to your user. +- [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) is a good fit when one URL has more than one correct response, such as a personalized page or a `POST` response. Cache then keeps a separate copy for each value of a query-string argument, a cookie, the device group, or the method. +- [Image Processor](/en/documentation/platform/applications/image-processor/) fits a page that needs one image in several sizes, crops, qualities, or formats, such as WEBP for browsers that accept it. Every variant then comes from one file on your origin, so you store and upload only that file. +- [Device Groups](/en/documentation/platform/applications/device-groups/) lets an Application tell apart the devices that send its requests, so a rule or a cache setting can treat each group differently. It needs Application Accelerator turned on in the Application. +- [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) is where you write what an Application does with each request it receives. For example, one rule can route `/api/` to one origin while a second rule routes every other path to another. +- [WebSocket Proxy](/en/documentation/platform/applications/websocket/) lets an Application carry a WebSocket connection between your users and your origin. Azion turns it on for an account only on request. +- A [Function Instance](/en/documentation/platform/applications/functions-instances/) lets an Application run one of your Functions. For example, the same Function can run in more than one Application, each Function Instance with its own arguments. - + --- ## Request path -Creating an Application routes no request to it: a Workload's deployment has to set that Application first. An Application also reaches an origin only through a rule that sets a Connector. The diagram follows a request that takes that path. In place of an origin, a Function can answer a request: a rule runs the Function with _Run Function_, and the Function builds the response with no Connector. +Creating an Application routes no request to it: a request reaches an Application only once a Workload's deployment sets that Application. The Application then reaches an origin only through a rule that sets a Connector. In place of an origin, a rule can run a Function that builds the response with no Connector. -Solid arrows carry the request, and dotted arrows carry the response. Each label starts with the number of its step below. +The diagram follows a request that reaches an origin. Solid arrows carry the request, and dotted arrows carry the response. Each label starts with the number of its step below. ```mermaid %%{init: {"layout": "elk", "elk": {"cycleBreakingStrategy": "MODEL_ORDER"}, "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% @@ -53,104 +61,11 @@ flowchart TD App -.->|"5. response"| Client ``` -1. The request reaches a Workload through one of its domains, and the Workload's deployment sets the Application. In Azion Console, you set it in the **Application** field of **Deployment Settings**. A [Firewall](/en/documentation/platform/firewall/) that the deployment also sets runs its rules first, and it can stop the request there. -2. The Application's Request Phase rules run in order. When a behavior, the action a rule runs, ends the processing, as _Deny (403 Forbidden)_ does, the Application answers the client, and no later rule runs. -3. If a rule with the _Set Cache Policy_ behavior applied a cache setting, [Cache](/en/documentation/platform/applications/cache/) looks for a valid copy of the origin response. When Cache holds one, that copy becomes the response, and the origin receives no request. -4. Otherwise, the Connector set by a rule with _Set Connector_ routes the request to the origin. If several matching rules carry _Set Connector_, only the last of them runs. -5. The Application's Response Phase rules then run on the response, and the response reaches the client. - -A new Application starts with Cache and [Functions](/en/documentation/platform/functions/) on, Application Accelerator and [Image Processor](/en/documentation/platform/applications/image-processor/) off, and no rules. - -A change does not take effect at once: it propagates, and Azion guarantees no propagation time. Until the deployment of a new Workload propagates, which can take several minutes, the Workload answers with Azion's placeholder `404`. During that time, answers alternate between the placeholder and the Application's response, so repeat the request until they agree. For how the two phases work, the order of rules and behaviors, and propagation, refer to [How Applications works](/en/documentation/platform/applications/how-it-works/). - ---- - -## Rule structure - -A rule is the unit of logic in an Application. Its criteria test each request, and its behaviors run on a request that matches. To route every request to the Connector that reaches your origin, send this rule as the body of `POST /v4/workspace/applications//request_rules`: - -```json -{ - "name": "send-to-origin", - "active": true, - "criteria": [ - [ - { - "variable": "${uri}", - "conditional": "if", - "operator": "starts_with", - "argument": "/" - } - ] - ], - "behaviors": [ - { - "type": "set_connector", - "attributes": { "value": } - } - ] -} -``` - -- `criteria` holds groups of conditions, and each group starts with a condition whose `conditional` is `if`. Here, `${uri}` is the URI without its query string. Every path starts with `/`, so `starts_with` and `/` match every request. If the rule tests `${request_uri}` instead, which keeps the query string, the API refuses it with `400` and error `25047` while [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) is off. -- `behaviors` lists the actions the rule runs on a matching request. `set_connector` routes the request to the Connector whose ID is in `attributes.value`. That Connector holds the address of your origin. -- `name` and `active` belong to the rule itself. -- You can also build the same rule in Azion Console, as [Applications quickstart](/en/documentation/platform/applications/quickstart/) shows. - -When you send the rule, the API answers `202` and returns it with `order` set to `0`. That value is the rule's position among the Request Phase rules of the Application. - -The model matches path-based routing in a reverse proxy: each criterion is a match condition, each behavior is an action, and a Connector holds the address of the backend server. - ---- - -## Resources - -Cache, Application Accelerator, and Image Processor act on the requests of an Application. Each Application turns Application Accelerator and Image Processor on separately, and [Main Settings](/en/documentation/platform/applications/main-settings/#platform-resources) shows where in Azion Console and the API. - -### Cache - -Cache is a Platform Resource that stores copies of the responses to the requests received by an Application. Each copy stays in the data center that stored it, and later requests for the same object get that copy until its time to live (TTL) ends. Cache is always on in an Application. It starts storing copies once a _Set Cache Policy_ rule applies a cache setting, which holds the TTLs. Use Cache to: - -- Keep static files in the data center nearest to your user -- Serve large video files in fragments, with Large File Optimization turned on in the cache setting -- Answer requests with an expired copy when the origin fails to answer, with stale cache turned on in the cache setting -- Remove a copy when the origin changes, with [Real-Time Purge](/en/documentation/platform/applications/cache/real-time-purge/) - -The [Cache overview](/en/documentation/platform/applications/cache/) explains what a cache setting holds, how a request reaches a stored copy, and where to start. - -### Application Accelerator - -Application Accelerator is a Platform Resource that unlocks four capabilities for the cache and the rules of an Application: cache variation, the caching of `POST` and `OPTIONS` responses, a Max Age below 60 seconds, and further Rules Engine behaviors and variables. With cache variation, a cache setting tells apart two requests for the same URL by a query-string argument, a cookie, the device group, or the request method, and Cache keeps a separate copy for each value. Application Accelerator starts off in a new Application. Turn it on when one URL has more than one correct response, for example: - -- A personalized page -- An API response that changes with its query string -- A catalog that differs by device -- A response to a `POST` - -The [Application Accelerator overview](/en/documentation/platform/applications/application-accelerator/) explains what a variation adds to the cache key, what turning it on unlocks, and where to start. - -### Image Processor - -Image Processor is a Platform Resource that builds a new image, the derived image, from an image on your origin. The `ims` query string of the request describes the derived image, such as `?ims=fit-in/400x400`, and even with no `ims` query string, Image Processor can convert an image to a format the browser accepts. It returns the derived image without saving it as an asset of the account. It starts off in a new Application, and even when it is on, Image Processor processes only the requests that a Request Phase rule with _Optimize Images_ matches. Turn it on when your pages need one image in several sizes, crops, qualities, or formats, such as WEBP for browsers that accept it. Every variant then comes from one file on your origin, so you store and upload only that file. - -The [Image Processor overview](/en/documentation/platform/applications/image-processor/) explains how a request becomes a derived image, what `ims` accepts, and where to start. - ---- - -## Scope and limits - -- **Phases**: every rule belongs to one of two phases. The Request Phase acts on the request before a response exists, and the Response Phase acts on the response that the user receives. You choose the phase when you create the rule, and you cannot change it later. Only Request Phase rules can choose the origin and the cache setting. [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/#phases) lists the variables and behaviors of each phase and the Platform Resource that each one needs. -- **Origins**: an Application reaches each origin through a Connector, so two rules with two Connectors can route `/api/` to one server and every other path to another. The origin behind a Connector can be a web server in your infrastructure, a cloud service, or an [Object Storage](/en/documentation/platform/object-storage/) bucket. [Use a bucket as an application origin](/en/documentation/guides/application-development/data/use-bucket-as-origin/) shows the bucket case. With [Load Balancer](/en/documentation/platform/connectors/load-balancer/) enabled, one Connector of the `http` type can spread traffic across several origins. Connectors replace the origins that earlier versions of Applications configured on the Application. -- **Functions**: a [Function Instance](/en/documentation/platform/applications/functions-instances/) binds one of your [Functions](/en/documentation/platform/functions/) to the Application, with its own arguments. A Function Instance belongs to one Application, and it runs only when a rule with _Run Function_ invokes that Function Instance. Functions starts on in a new Application, in its `modules.functions.enabled` field in the API. Only Functions written in Lua run in the Response Phase, as the Function Instance form in Azion Console states: `Only Lua functions can be used in the Response phase.` For the steps to add your first Function, refer to [Instantiate a function on an application](/en/documentation/guides/application-development/getting-started/instantiate-functions/). -- **Cache and images in code**: code that reads or writes cached entries runs in a Function and uses the [Cache API](/en/documentation/devtools/runtime/api-reference/cache/), because Cache itself cannot run code. A Function that processes images on its own uses the WASM Image Processor library, which is separate from the Image Processor Platform Resource. [Where Image Processor stops](/en/documentation/platform/applications/image-processor/image-delivery/#where-image-processor-stops) explains the difference. -- **Devices**: a [device group](/en/documentation/platform/applications/device-groups/) is a name and a regular expression that the Application compares with the `User-Agent` header of each request. Both uses of a group need Application Accelerator on: a rule tests the group through `${device_group}`, and a cache setting can keep one copy per group. [Applications best practices](/en/documentation/platform/applications/best-practices/#match-a-device-group-on-the-words-that-only-that-device-sends) shows how to write an expression that matches only the devices you mean. -- **WebSocket**: [WebSocket Proxy](/en/documentation/platform/applications/websocket/) is a Feature of Applications that carries a WebSocket connection between your users and the origin. The connection opens with the `Upgrade: websocket` and `Connection: upgrade` headers. Azion turns the Feature on for an account only on request, and [Support guidelines](/en/documentation/support/) explains how to ask. Because Azion recycles keepalive connections about every 15 minutes, the client must reopen a WebSocket connection when it closes. -- **Workloads**: a Workload holds the domains, protocols, and certificates that serve the Application, so you configure delivery on the Workload, not on the Application. [Test an application through the hosts file](/en/documentation/guides/application-development/getting-started/stage-applications-through-hosts-file/) shows how to request an Application on your own domain from one device before you change its DNS records. _Redirect HTTP to HTTPS_ works only when the Workload has HTTPS. When the Connector receives a 4xx or 5xx response from your origin, [Custom Pages](/en/documentation/platform/custom-pages/) on the Workload sets the error page that the client sees. -- **Interfaces**: in [Azion Console](https://console.azion.com/), you create and manage your Applications on the **Applications** page, where each Application has five tabs: **Main Settings**, **Device Groups**, **Cache Settings**, **Functions Instances**, and **Rules Engine**. In the Console, the **Clone** row action of the **Applications** list creates a separate Application with the settings of the original, as [Clone an application](/en/documentation/guides/application-development/getting-started/clone-applications/) shows. The [Azion API](https://api.azion.com/) serves your Applications at `/v4/workspace/applications`, and [Azion CLI](/en/documentation/devtools/cli/) manages them with commands such as `azion create application`, `azion update application`, and `azion create rules-engine`. You can also create and configure your Applications with [`azion.config.js`](/en/documentation/devtools/cli/azion-config-js/), [Azion Lib](/en/documentation/devtools/azion-lib/application/), or the [Azion Terraform Provider](/en/documentation/devtools/terraform/). If your account has not migrated to API v4, use [Applications | v3](/en/documentation/platform/applications/v3/). -- **Observability**: with Debug Rules on, [Real-Time Events](/en/documentation/platform/real-time-events/) and [Data Stream](/en/documentation/platform/data-stream/) show the rules that each request ran, in the `$traceback` field. Debug Rules starts off in a new Application. It is the `debug` field of the Application in the API, and [Main Settings](/en/documentation/platform/applications/main-settings/#debug-rules) shows where to turn it on in Azion Console. To check one response, send the request with `Pragma: azion-debug-cache`: the response reports its cache status, such as `HIT` or `MISS`, in the `x-cache` header. Across all requests, [Real-Time Metrics](/en/documentation/platform/real-time-metrics/) shows the traffic of Cache and [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/). [Troubleshoot Applications](/en/documentation/platform/applications/troubleshooting/) lists the tools and queries. For traffic that differs from what you see, refer to [A problem shows in traffic but not in the responses you request](/en/documentation/platform/applications/troubleshooting/#a-problem-shows-in-traffic-but-not-in-the-responses-you-request). -- **Limits**: an Application accepts at most 200 rules, counting both phases. Each rule has 1 to 5 groups of 1 to 10 criteria, plus 1 to 10 behaviors. Without Application Accelerator, a cache setting needs a Max Age, its `modules.cache.max_age` field, of at least 60 seconds. One cached object can be as large as 10 GB. [Applications limits](/en/documentation/platform/applications/limits/) lists every bound, what happens past it, and the bounds of each Platform Resource nested in Applications. -- **Billing**: a Platform Resource that you turn on can add costs that depend on usage. [Azion pricing](https://www.azion.com/en/pricing/) lists the plans and the usage that each plan includes, and [Pricing](/en/documentation/fundamentals/pricing/) lists the rates and the metric that each Platform Resource is billed on. -- **Terms**: the [Applications glossary](/en/documentation/platform/applications/glossary/) defines the words that the Applications pages use with a specific meaning, such as rule, phase, behavior, cache setting, cache key, and derived image. +1. The request reaches a Workload through one of its domains, and the Workload forwards it to the Application. When the Workload's deployment also sets a [Firewall](/en/documentation/platform/firewall/), the Firewall runs its rules first and can refuse the request. +2. The Application runs its Request Phase rules in order. When a behavior, the action a rule runs, ends the processing, as _Deny (403 Forbidden)_ does, the Application answers the client, and no later rule runs. +3. A rule with _Set Cache Policy_ can apply a cache setting, the set of values that tells Cache how to store and serve a response. Cache then looks for a valid copy of the origin response. If Cache holds one, that copy becomes the response, and the origin receives no request. +4. Otherwise, the Connector that a rule with _Set Connector_ sets routes the request to the origin. If several matching rules carry _Set Connector_, only the last of them runs. +5. The Application runs its Response Phase rules on the response, and the response reaches the client. --- @@ -159,8 +74,10 @@ The [Image Processor overview](/en/documentation/platform/applications/image-pro - + - + + + diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/edge-functions-instances.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/edge-functions-instances.mdx index 78f83a17dd..48d14f65d1 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/edge-functions-instances.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/edge-functions-instances.mdx @@ -14,15 +14,17 @@ import DocItem from '@aziontech/webkit/doc-item' A Function Instance is the entity that binds one [Function](/en/documentation/platform/functions/) to one [Application](/en/documentation/platform/applications/) or one [Firewall](/en/documentation/platform/firewall/). The Function Instance carries the Args, the arguments passed into the context of the Function's execution in JSON format: `args` in the API, and the **Arguments** section in Azion Console. A Function Instance sets its name, its Args, its form schema, and whether it is active, and it leaves the code of the Function as it is. -A rule in [Rules Engine](/en/documentation/platform/applications/rules-engine/) invokes the Function Instance, not the Function. The same Function can be instantiated in more than one Application, and each Function Instance carries its own Args. A Function Instance runs only when a rule with _Run Function_ invokes that Function Instance. +The same Function can be instantiated in more than one Application, and each Function Instance carries its own Args. A Function Instance runs only when a rule in [Rules Engine](/en/documentation/platform/applications/rules-engine/) invokes that Function Instance, not the Function, with _Run Function_. -A Firewall holds its own Function Instances. A Function Instance on a Firewall runs its Function before the request reaches the Application, so the Function can stop the request there. A Function Instance on an Application runs its Function as part of serving the request. For the Function Instances of a Firewall, refer to [Function instances for Firewall](/en/documentation/platform/firewall/functions-instances/). For their bounds, refer to [Firewall limits](/en/documentation/platform/firewall/limits/#rules-and-function-instances). +A Firewall holds its own Function Instances. A Function Instance on a Firewall runs its Function before the request reaches the Application, so the Function can stop the request there. A Function Instance on an Application runs its Function as part of serving the request. + +For the Function Instances of a Firewall, refer to [Function instances for Firewall](/en/documentation/platform/firewall/functions-instances/). For their bounds, refer to [Firewall limits](/en/documentation/platform/firewall/limits/#rules-and-function-instances). --- ## Function Instance fields -The [Azion API](https://api.azion.com/) creates a Function Instance of an Application under that Application. These are the fields you set: +You create a Function Instance of an Application through the [Azion API](https://api.azion.com/), under the path of that Application. These are the fields you set: | Field | Type | Required | Description | | --- | --- | --- | --- | @@ -75,7 +77,7 @@ The API answers `202` with the created object: } ``` -The `"state": "pending"` value means the change takes a few minutes to propagate before it takes effect. +The `"state": "pending"` value means the change can take a few minutes to propagate before it takes effect, and Azion guarantees no propagation time. The API serves the Function Instances of an Application under `/workspace/applications//functions`. In the path of one Function Instance, `` is the ID of the Function Instance, not of the Function: @@ -114,7 +116,7 @@ Args are the configuration of one Function Instance. Sensitive values such as AP _Run Function_ is the [Rules Engine](/en/documentation/platform/applications/rules-engine/#run-function) behavior that invokes a Function Instance. The rule holds the ID of the Function Instance, and the phase and the criteria of the rule decide when it runs. When a request meets those criteria, the Function runs on Azion's distributed infrastructure. -_Run Function_ is available in the Request Phase and in the Response Phase, and it requires [Functions](/en/documentation/platform/functions/) turned on in the Application. In the Response Phase, it runs only Functions written in Lua. In the Azion API, the behavior is `run_function`, and its `value` attribute holds the ID of the Function Instance. While Functions is off, the API also refuses to create a Function Instance in the Application, with HTTP `400` and error `29003`, `Edge Functions Module Is Not Enabled`. +_Run Function_ is available in the Request Phase and in the Response Phase, and it requires [Functions](/en/documentation/platform/functions/) turned on in the Application. In the Response Phase, it runs only Functions written in Lua. In the Azion API, the behavior is `run_function`, and its `value` attribute holds the ID of the Function Instance. For the execution phases, the criteria, and the order behaviors run in, refer to [How Functions works](/en/documentation/platform/functions/how-it-works/). @@ -136,6 +138,16 @@ Azion CLI manages the Function Instances of an Application with five commands un --- +## Errors + +The API refuses a Function Instance with this error: + +| Code | Title | Status | What causes it | What to do | +| --- | --- | --- | --- | --- | +| `29003` | `Edge Functions Module Is Not Enabled` | 400 | A new Function Instance in an Application with Functions off | Turn on Functions in the Application, then create the Function Instance again | + +--- + ## Related resources diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/first-steps.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/first-steps.mdx index cd877434e4..57c353f4f5 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/first-steps.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/first-steps.mdx @@ -22,15 +22,17 @@ This guide instructs you through serving your origin's content from your first [ Five parts make the chain, listed in the order this guide uses them: -1. The **Connector** holds the address of your origin and the way Azion connects to it. -2. The **Application** holds the rules that decide what happens to a request. A new Application has no rules. -3. The **rule** on the Application pairs a condition on the request, called a criterion, with an action called a behavior. In this guide, the criterion matches every request, and the _Set Connector_ behavior sends the request to the Connector. -4. The **Workload** holds a domain and receives the requests sent to it. Its **deployment**, a setting of the Workload, sets the Application that receives those requests. +1. The **Connector** holds the address of your origin and the settings Azion uses to reach it. +2. The **Application** processes the requests that the Workload receives, and its rules decide what happens to each request. A new Application has no rules. +3. The **rule** is an entry in Rules Engine for Applications that runs its behaviors, in one phase, on the requests its criteria match. A criterion is a condition on the request, and a behavior is the action the rule runs. In this guide, the criterion matches every request, and the _Set Connector_ behavior sends the request to the Connector. +4. The **Workload** holds a domain and receives the requests sent to it. Its **deployment** is the part of the Workload that sets the Application that receives those requests. 5. The **request** goes to the workload domain, the hostname Azion assigns to the Workload. The rule of the Application matches the request, and the Connector routes it to your origin. A Connector receives requests only after a rule sets that Connector. An Application receives the requests of a Workload only after that Workload's deployment sets that Application. -Each Application has four switches: [Cache](/en/documentation/platform/applications/cache/), [Functions](/en/documentation/platform/functions/), [Application Accelerator](/en/documentation/platform/applications/application-accelerator/), and [Image Processor](/en/documentation/platform/applications/image-processor/). In Azion Console, the switches are in **Main Settings** > **Modules**, and in the API, they are the keys of `modules`. A new Application starts with Cache and Functions turned on and the other two turned off, and this guide keeps all four as they are. The quickstarts of Cache, Application Accelerator, and Image Processor begin where this guide ends, with an Application that already serves content. +Each Application has four switches: [Cache](/en/documentation/platform/applications/cache/), [Functions](/en/documentation/platform/functions/), [Application Accelerator](/en/documentation/platform/applications/application-accelerator/), and [Image Processor](/en/documentation/platform/applications/image-processor/). In Azion Console, the switches are in **Main Settings** > **Modules**, and in the API, they are the keys of `modules`. A new Application starts with Cache and Functions turned on and the other two turned off, and this guide keeps all four as they are. + +The quickstarts of Cache, Application Accelerator, and Image Processor begin where this guide ends, with an Application that already serves content. --- @@ -248,7 +250,7 @@ The Connector is active, and its address takes HTTPS connections on `https_port` ## Create the Application -An Application holds the rules that decide what happens to each request. It needs only a name, and every other setting keeps its default. The Application reaches your origin only through a rule that sets a Connector. +An Application processes the requests received by a Workload, and its rules decide what happens to each request. It needs only a name, and every other setting keeps its default. The Application reaches your origin only through a rule that sets a Connector. @@ -346,7 +348,9 @@ The Application is active and has no rules. In `modules`, `cache` and `functions ## Send every request to the Connector -A rule in [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) pairs criteria with behaviors. This rule runs in the Request Phase. Its criterion, `${uri}` starting with `/`, matches every request. Its behavior, _Set Connector_, sends each matching request to your Connector. For more information, refer to [Set Connector](/en/documentation/platform/applications/rules-engine/#set-connector). +A rule in [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/) runs its behaviors, in one phase, on the requests its criteria match. This rule runs in the Request Phase, and its criterion, `${uri}` starting with `/`, matches every request. + +The behavior of this rule, _Set Connector_, sends each matching request to your Connector. For more information, refer to [Set Connector](/en/documentation/platform/applications/rules-engine/#set-connector). The criterion uses `${uri}`, not `${request_uri}`. `${request_uri}` needs Application Accelerator turned on. On an Application with Application Accelerator turned off, the API refuses the rule with `400` and error `25047`, `Missing Required Modules`. @@ -521,7 +525,7 @@ The response carries the stored rule. This excerpt keeps its `id`, its criterion ## Serve the Application from a Workload -A Workload receives the requests sent to its domains. It holds those domains, the protocols, and the certificates, so you configure delivery on the Workload, not on the Application. The Workload's deployment sets the Application that receives those requests, and a Workload holds one deployment. A new Workload answers on a workload domain that Azion assigns under `map.azionedge.net`. +A Workload receives the requests sent to its domains. It holds those domains, the protocols, and the certificates, so you configure delivery on the Workload, not on the Application. The Workload's deployment sets the Application that receives those requests, and a Workload holds at most one deployment. A new Workload answers on a workload domain that Azion assigns under `map.azionedge.net`. @@ -595,7 +599,7 @@ ID CURRENT EDGE APPLICATION EDGE FIREWALL true 0 ``` -The deployment of the Workload sets your Application. A project that declares the Workload in `azion.config.js` gets its deployment from `azion deploy` instead, and that deployment sets the Application the deploy creates for the project, even when the [`deployments`](/en/documentation/devtools/cli/azion-config-js/#workload-deployments) entry names another Application by its ID. +The deployment of the Workload sets your Application. A project that declares the Workload in `azion.config.js` gets its deployment from `azion deploy` instead. That deployment sets the Application the deploy creates for the project, even when the [`deployments`](/en/documentation/devtools/cli/azion-config-js/#workload-deployments) entry names another Application by its ID. To find the workload domain, describe the Workload in JSON: @@ -619,7 +623,9 @@ In the output, the `workload_domain` field holds the domain that the final reque ### API -To create the Workload with the API, send a `POST` request to the workloads endpoint. `infrastructure` set to `1` selects the production infrastructure, and `workload_domain_allow_access` set to `true` lets the Workload answer on its workload domain. Replace `[TOKEN VALUE]` with your personal token: +To create the Workload with the API, send a `POST` request to the workloads endpoint. + +`infrastructure` set to `1` selects the production infrastructure, and `workload_domain_allow_access` set to `true` lets the Workload answer on its workload domain. Replace `[TOKEN VALUE]` with your personal token: ` with the `id` of the Workload and `` with the ID of your Application: + + --name first-deployment --application-id `} /> + +The command prints the ID of the new deployment: + +```text +Created Workload Deployment with ID +``` + +The deployment of the Workload sets your Application. @@ -680,7 +696,9 @@ To set your Application in the deployment of the Workload you created, run the c This stage needs only `curl`, whichever interface you used to build the chain. In the command, replace `` with the workload domain of the Workload you created. -A new Workload answers with your origin's response only after its first deployment reaches traffic. This can take several minutes, and Azion guarantees no duration. Until then, the workload domain answers `404` with a placeholder page. While the deployment spreads, answers to the same request can alternate between that `404` and your origin's response. Repeat the request until the answer comes from your origin. For more information, refer to [Propagation](/en/documentation/platform/applications/how-it-works/#propagation). +A new Workload answers with your origin's response only after its first deployment reaches traffic. This can take several minutes, and Azion guarantees no duration. Until then, the workload domain answers `404` with a placeholder page. + +While the deployment spreads, answers to the same request can alternate between that `404` and your origin's response. Repeat the request until the answer comes from your origin. For more information, refer to [Propagation](/en/documentation/platform/applications/how-it-works/#propagation). Send a request to the root path of your workload domain: diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/l2-caching.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/l2-caching.mdx index c744c39b55..7bea7767a9 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/l2-caching.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/l2-caching.mdx @@ -14,9 +14,7 @@ import DocItem from '@aziontech/webkit/doc-item' **Tiered Cache** is a Feature of [Cache](/en/documentation/platform/applications/cache/) that adds a second cache layer between the data center that answers a request and your origin. The first layer is the cache of that data center. The second layer sits in the region that the `topology` of a cache setting selects. -When a request misses the first layer, the data center asks the Tiered Cache layer before the request goes to the origin. A valid copy of the requested object in that layer answers the miss, and the origin receives no request. You turn the layer on per cache setting, and it applies to the objects that setting caches. For how the two layers answer a request, refer to [Expiration and freshness](/en/documentation/platform/applications/cache/expiration-and-freshness/#tiered-cache). - -An answer from the Tiered Cache layer arrives with less latency than one from the origin, and fewer requests reach the origin. The origin handles less load at a lower infrastructure cost. The price is one extra hop on a miss in the first layer. With [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) on, Tiered Cache also sets a floor of 3 seconds on the time to live (TTL) of the cache setting. +You turn the layer on per cache setting, and it applies to the objects that setting caches. For how the two layers answer a request, and what the layer costs and saves, refer to [Expiration and freshness](/en/documentation/platform/applications/cache/expiration-and-freshness/#tiered-cache). --- @@ -26,13 +24,15 @@ A cache setting turns Tiered Cache on in its `modules.cache.tiered_cache` object | Interface | Where | Value | | --- | --- | --- | -| [Azion Console](https://console.azion.com/) | The **Cache** section of the **Create Cache Settings** drawer, under the **Cache Settings** tab of an Application in [Applications](/en/documentation/platform/applications/) | The **Tiered Cache** toggle, off on a new setting, and the **Tiered Cache Region** select, `nearest-region` by default. Turning the toggle on disables _Honor cache policies_ and selects _Override cache behavior_ | +| [Azion Console](https://console.azion.com/) | The **Cache** section of the **Create Cache Settings** drawer, under the **Cache Settings** tab of an Application in [Applications](/en/documentation/platform/applications/) | The **Tiered Cache** toggle, off on a new setting, and the **Tiered Cache Region** select, `nearest-region` by default | | [Azion API v4](/en/documentation/devtools/api/) | `POST /v4/workspace/applications/{application_id}/cache_settings` | `modules.cache.tiered_cache.enabled`, `true` or `false`, and `modules.cache.tiered_cache.topology`, `nearest-region` when the body leaves it out | | [Azion CLI](/en/documentation/devtools/cli/) | `azion create cache-setting --file` with the JSON body | The same `tiered_cache` object. The `--tiered-caching-enabled` flag alone is refused with error `21001` | | `azion.config.js` | An entry of the `cache` array, of type `AzionCache` | `tieredCache: { enabled, topology }` | :::note -Two conditions bind the cache setting. Its `modules.cache.behavior` must be `override`, because the API refuses Tiered Cache under `honor` with error `21001`. The CLI sets the cache behavior only in the JSON body of `--file`. With [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) on the Application, the `modules.cache.max_age` of the cache setting must be at least 3 seconds, or the API returns error `21020`. Without Application Accelerator, the 60-second floor of every cache setting holds, and the API returns `21021`. +A cache setting with Tiered Cache on needs `override` in `modules.cache.behavior`, because the API refuses Tiered Cache under `honor` with error `21001`. In Azion Console, turning the **Tiered Cache** toggle on disables _Honor cache policies_ and selects _Override cache behavior_. The CLI sets the cache behavior only in the JSON body of `--file`. + +With [Application Accelerator](/en/documentation/platform/applications/application-accelerator/) on the Application, the `modules.cache.max_age` of the cache setting must be at least 3 seconds, or the API returns error `21020`. Without Application Accelerator, the 60-second floor of every cache setting holds, and the API returns `21021`. ::: Tiered Cache is included on every service plan. For every field of a cache setting, with the title and the fix of each error, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/). For the Console steps that apply a setting to a path, refer to [Configure cache policies for an application](/en/documentation/guides/application-performance/cache-and-purge/cache-settings/). @@ -47,7 +47,9 @@ The `topology` of a cache setting selects where the Tiered Cache layer holds the ## TTL -The time to live (TTL) of an object in the Tiered Cache layer is the Max Age of its cache setting, the `modules.cache.max_age` field. While Tiered Cache and Application Accelerator are both on, that field has a floor of 3 seconds. A new cache setting starts at 60 seconds, the default of Max Age in Azion Console, the API, and the CLI. For example, on an Application with Application Accelerator on, a Max Age of 2 seconds with Tiered Cache on is refused with error `21020`. The same setting at 3 seconds is accepted. +The time to live (TTL) of an object in the Tiered Cache layer is the Max Age of its cache setting, the `modules.cache.max_age` field. While Tiered Cache and Application Accelerator are both on, that field has a floor of 3 seconds. A new cache setting starts at 60 seconds, the default of Max Age in Azion Console, the API, and the CLI. + +For example, on an Application with Application Accelerator on, a Max Age of 2 seconds with Tiered Cache on is refused with error `21020`. The same setting at 3 seconds is accepted. The ceiling is the ceiling of the cache TTL itself. For the value and the error past it, refer to [Applications limits](/en/documentation/platform/applications/limits/#cache). diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/main-settings.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/main-settings.mdx index 5de7c90249..73c947c66a 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/main-settings.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/main-settings.mdx @@ -17,9 +17,28 @@ Main Settings is the set of values that apply to an [Application](/en/documentat --- +## Interfaces + +You create and configure an Application in Azion Console, the Azion API, Azion CLI, `azion.config.js`, Azion Lib, or the Azion Terraform Provider. + +| Interface | Where it reaches your Applications | +| --- | --- | +| [Azion Console](https://console.azion.com/) | The **Applications** page, with five tabs for each Application | +| [Azion API](https://api.azion.com/) | `/v4/workspace/applications`, which the API section details | +| [Azion CLI](/en/documentation/devtools/cli/) | Commands such as `azion create application`, `azion update application`, and `azion create rules-engine` | +| [`azion.config.js`](/en/documentation/devtools/cli/azion-config-js/) | The configuration file that Azion CLI reads | +| [Azion Lib](/en/documentation/devtools/azion-lib/application/) | Creates and configures Applications from your code | +| [Azion Terraform Provider](/en/documentation/devtools/terraform/) | Creates and configures Applications | + +In Azion Console, each Application has five tabs: **Main Settings**, **Device Groups**, **Cache Settings**, **Functions Instances**, and **Rules Engine**. This page documents the **Main Settings** tab. The **Clone** row action of the **Applications** list creates a separate Application with the settings of the original. To clone one, refer to [Clone an application](/en/documentation/guides/application-development/getting-started/clone-applications/). + +An account that has not migrated to API v4 manages its Applications in [Applications | v3](/en/documentation/platform/applications/v3/). + +--- + ## Sections and fields -In Azion Console, the **Main Settings** tab of an Application has four sections: **General**, **Modules**, **Debug Rules**, and **Status**. The tab carries **Cancel** and **Save**, and a change is saved with **Save**. +In Azion Console, the **Main Settings** tab of an Application has four sections: **General**, **Modules**, **Debug Rules**, and **Status**. The tab carries **Cancel** and **Save**, and **Save** keeps a change. Each section maps to one or more fields of the Application in the API. The last column holds the value each field takes when a create request sends only `name` and `active`. @@ -38,22 +57,26 @@ The status, the `active` boolean in the API, turns the Application off and back ## Platform Resources -In Azion Console, the switches that turn Platform Resources on or off for one Application sit in the **Modules** section, and each Application keeps its own set. Its **Default Modules** group holds one switch per Platform Resource: **Application Accelerator**, **Cache**, **Functions**, and **Image Processor**. A **Subscription modules** group carries a **Contact sales** action, and the section states `Some modules require subscription.` +Each Application turns on its own set of four Platform Resources, in the `modules` object of the API and the **Modules** section of Azion Console. The **Default Modules** group of that section holds one switch per Platform Resource: **Application Accelerator**, **Cache**, **Functions**, and **Image Processor**. A **Subscription modules** group carries a **Contact sales** action, and the section states `Some modules require subscription.` | Platform Resource | Key in `modules` | CLI flag | What it covers in the Application | | --- | --- | --- | --- | -| Application Accelerator | `application_accelerator` | `--application-accelerator` | The behaviors marked `- Required Application Accelerator`, and the `${request_uri}` variable | +| Application Accelerator | `application_accelerator` | `--application-accelerator` | The behaviors marked `- Required Application Accelerator`, and the `${request_uri}` and `${device_group}` variables | | Cache | `cache` | `--cache` | Caching of the content the Application delivers | | Functions | `functions` | `--function` on create, `--functions` on update | Function Instances, invoked by a _Run Function_ behavior | | [Image Processor](/en/documentation/platform/applications/image-processor/) | `image_processor` | `--image-processor` | The _Optimize Images_ behavior | -In Azion Console, the **Rules Engine** form marks a behavior whose Platform Resource is off with `- Required Application Accelerator`, `- Required Function`, or `- Required Image Processor`. A cache setting also needs Application Accelerator for the variations in its `modules.application_accelerator` object, and for a Max Age, its `modules.cache.max_age` field, below 60 seconds. +In Azion Console, the **Rules Engine** form marks a behavior whose Platform Resource is off with `- Required Application Accelerator`, `- Required Function`, or `- Required Image Processor`. Cache settings and Function Instances belong to the Application, outside Main Settings. A _Set Cache Policy_ behavior applies a cache setting, and a _Run Function_ behavior invokes a Function Instance. [Cache quickstart](/en/documentation/platform/applications/cache/quickstart/) and [Instantiate a function on an application](/en/documentation/guides/application-development/getting-started/instantiate-functions/) show where to create each one in Azion Console. -Cache is always on in an Application: the API refuses `modules.cache.enabled` set to `false` with error `31001`, `Cache Cannot Be False`. Azion Console shows the **Cache** switch locked on, with the note `Automatically enabled in all accounts.` You can turn another Platform Resource on when your account supports it, and off when nothing in the Application depends on it. Turning on a Platform Resource can generate usage-related costs. For more information, refer to [Pricing](/en/documentation/fundamentals/pricing/). +:::note +Cache is always on in an Application: the API refuses `modules.cache.enabled` set to `false` with error `31001`, `Cache Cannot Be False`. Azion Console shows the **Cache** switch locked on, with the note `Automatically enabled in all accounts.` +::: + +You can turn another Platform Resource on when your account supports it, and off when nothing in the Application depends on it. Turning on a Platform Resource can generate usage-related costs. For more information, refer to [Pricing](/en/documentation/fundamentals/pricing/). -While Application Accelerator is off, the API refuses a request rule whose criterion reads `${request_uri}`. It also refuses a cache setting that varies the cache by method, query string, cookie, or device group, or that sets a Max Age below 60 seconds. Each refusal carries one of the codes in Errors, and the same rule on `${uri}` is accepted. For the variables and behaviors each Platform Resource adds, refer to [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/). +While Application Accelerator is off, the API refuses a request rule whose criterion reads `${request_uri}` or `${device_group}`. It also refuses a cache setting that varies the cache by method, query string, cookie, or device group, in its `modules.application_accelerator` object, or that sets a Max Age, its `modules.cache.max_age` field, below 60 seconds. Each refusal carries one of the codes in Errors, and the same rule on `${uri}` is accepted. For the variables and behaviors each Platform Resource adds, refer to [Rules Engine for Applications](/en/documentation/platform/applications/rules-engine/). [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) is not one of the four `modules` switches of an Application: it is a Feature of Cache, and each cache setting turns it on in its `modules.cache.tiered_cache.enabled` field. @@ -61,7 +84,7 @@ While Application Accelerator is off, the API refuses a request rule whose crite ## Debug Rules -Debug Rules logs the Rules Engine rules that run on each request to the Application. The setting is off when you create an Application, and the API holds it in the `debug` boolean. In Azion Console, the **Active** switch of the **Debug Rules** section sets it. In [Azion CLI](/en/documentation/devtools/cli/), `--debug-enabled` sets it on `azion create application` and `azion update application`. +Debug Rules is the setting of an Application that logs the Rules Engine rules each request runs. The setting is off when you create an Application, and the API holds it in the `debug` boolean. In Azion Console, the **Active** switch of the **Debug Rules** section sets it. In [Azion CLI](/en/documentation/devtools/cli/), `--debug-enabled` sets it on `azion create application` and `azion update application`. With Debug Rules on, the rules that ran on a request appear in the `$traceback` field of [Data Stream](/en/documentation/platform/data-stream/) and [Real-Time Events](/en/documentation/platform/real-time-events/). The Real-Time Events GraphQL API returns the same rules in the `stacktrace` field. A rule that is missing from that list did not run on the request. @@ -149,7 +172,11 @@ The API answers `202` with `state` set to `pending`. A body with `functions` in | `azion delete application` | Deletes the Application that `--application-id` names | `--application-id`, `--cascade` | | `azion clone application` | Copies an Application under the name in `--name` | `--application-id`, `--name` | -The Functions flag is `--function` on `azion create application` and `--functions` on `azion update application`. On `azion delete application`, `--cascade` also deletes the resources that `azion deploy` created, and it defaults to `true`. +The Functions flag is `--function` on `azion create application` and `--functions` on `azion update application`. + +:::caution +On `azion delete application`, `--cascade` also deletes the resources that `azion deploy` created, and it defaults to `true`. +::: This command turns on Application Accelerator: @@ -182,7 +209,7 @@ On an Application with all four Platform Resources on, the object reads: ## Errors -A Platform Resource that is off in the Application surfaces as a refusal of the object that needs it, with `400`. Each of these refusals names Application Accelerator, except `31001`, which refuses turning Cache off. This body answers a request rule on `${request_uri}`: +A Platform Resource that is off in the Application surfaces as a refusal of the object that needs it, with `400` or `403`. Each of these refusals names the Platform Resource to turn on, except `31001`, which refuses turning Cache off. This body answers a request rule on `${request_uri}`: ```json { @@ -207,11 +234,15 @@ A Platform Resource that is off in the Application surfaces as a refusal of the | Code | Title | Status | What causes it | What to do | | --- | --- | --- | --- | --- | -| `25047` | `Missing Required Modules` | 400 | A request rule whose criteria read `${request_uri}`, on an Application with Application Accelerator off | Turn on Application Accelerator, or match on `${uri}`, which the API accepts without it | -| `21013` | `This Configuration Requires The Edge Application's Application Accelerator Module` | 400 | A cache setting that varies the cache by method, query string, cookie, or device group, on an Application with Application Accelerator off. The pointer names the variation, such as `/data/modules/application_accelerator/cache_vary_by_method` | Turn on Application Accelerator, then save the cache setting again | -| `21021` | `Edge Cache Max Age Lower Than The Minimum Allowed By Application's Application Accelerator Module` | 400 | A cache setting whose `modules.cache.max_age` is below 60, on an Application with Application Accelerator off. `meta.min_value` is `60` | Turn on Application Accelerator, or set `modules.cache.max_age` to 60 seconds or more | +| `25047` | `Missing Required Modules` | 400 | A rule on `${request_uri}` or `${device_group}`, with Application Accelerator off | Turn on Application Accelerator, or match on `${uri}`, which the API accepts without it | +| `21013` | `This Configuration Requires The Edge Application's Application Accelerator Module` | 400 | A cache variation by method, query string, cookie, or device group, with Application Accelerator off | Turn on Application Accelerator, then save the cache setting again | +| `21021` | `Edge Cache Max Age Lower Than The Minimum Allowed By Application's Application Accelerator Module` | 400 | A cache setting with `modules.cache.max_age` below 60, with Application Accelerator off | Turn on Application Accelerator, or set `modules.cache.max_age` to 60 seconds or more | +| `27002` | `Application Acceleration Not Enabled` | 403 | A new device group, with Application Accelerator off | Turn on Application Accelerator, then create the device group again | +| `29003` | `Edge Functions Module Is Not Enabled` | 400 | A new Function Instance, with Functions off | Turn on Functions, then create the Function Instance again | | `31001` | `Cache Cannot Be False` | 400 | A `PATCH` that sets `modules.cache.enabled` to `false` | Leave Cache on: it cannot be turned off | +For `21013`, the pointer names the variation, such as `/data/modules/application_accelerator/cache_vary_by_method`. For `21021`, `meta.min_value` is `60`. + --- ## Related resources diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/real-time-purge.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/real-time-purge.mdx index f381b06a86..47559cd357 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/real-time-purge.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/real-time-purge.mdx @@ -12,9 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Real-Time Purge** is a Platform Resource that removes a cached object from [Cache](/en/documentation/platform/applications/cache/), or from [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/), before its time to live (TTL) ends. Once the object is in neither Cache nor Tiered Cache, the next request for it fetches the current version from the origin. Use a purge to serve an update the origin already has, to remove an obsolete object, or to keep control of what Azion serves for dynamic content. - -A purge takes one of three arguments: a list of URLs, a list of cache keys, or one wildcard expression. Azion confirms each purge, queues it, and lists it in the purge history when it is complete. For the steps, refer to [Purge cached content](/en/documentation/guides/application-performance/cache-and-purge/purge-cached-content/). For the format of a key, refer to [Cache keys](/en/documentation/platform/applications/cache/cache-keys/). +**Real-Time Purge** is a Platform Resource that removes a cached object from [Cache](/en/documentation/platform/applications/cache/) or the [Tiered Cache](/en/documentation/platform/applications/cache/tiered-cache/) layer before its time to live (TTL) ends. Once the object is in neither layer, the next request for it fetches the current version from the origin. A purge takes one of three arguments: a list of URLs, a list of cache keys, or one wildcard expression. For the steps, refer to [Purge cached content](/en/documentation/guides/application-performance/cache-and-purge/purge-cached-content/), and for the format of a key, to [Cache keys](/en/documentation/platform/applications/cache/cache-keys/). --- @@ -59,9 +57,9 @@ The `purge_type` segment of the API path, the CLI flag, and the Console's purge ### URL purge -A URL purge takes a list of URLs and is not recursive: only the URLs in the list leave the cache. Azion converts each URL to its cache key with no content variation. So a variation by cookie, device group, image format, or request body does not expire with it. Purge those variations with a cache key or a wildcard. +A URL purge takes a list of URLs and is not recursive: only the URLs in the list leave the cache. Azion converts each URL to its cache key with no content variation. So a copy that varies by cookie, device group, image format, or request body does not expire with it. Purge those copies with a cache key or a wildcard. -A variation by query string is part of the URL, so it expires when the arguments are in the same order as in the cache key. With `sort_enabled` on in the cache setting, send the arguments in alphabetical order, or use a cache key or wildcard purge. For the `sort_enabled` field, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#application-accelerator). +A copy that varies by query string carries the arguments in its URL, so it expires when the arguments are in the same order as in the cache key. With `sort_enabled` on in the cache setting, send the arguments in alphabetical order, or use a cache key or wildcard purge. For the `sort_enabled` field, refer to [Cache settings](/en/documentation/platform/applications/cache/cache-settings/#application-accelerator). A URL is `scheme://host` or `host`, with an optional `/path` and `?query-string`. Without a scheme, Azion purges both the HTTP and the HTTPS copies. An asterisk (`*`) in a URL purge is a literal character, not a wildcard. The list below carries four valid URL arguments: @@ -72,11 +70,15 @@ A URL is `scheme://host` or `host`, with an optional `/path` and `?query-string` ### Cache key purge -A cache key purge takes a list of cache keys. A key names one variation of an object. With Advanced Cache Key, a Feature of [Application Accelerator](/en/documentation/platform/applications/application-accelerator/), a key can vary by query string, sorted or not, and by cookie, device group, or request method. Through [Image Processor](/en/documentation/platform/applications/image-processor/), a key can also vary by image format. To purge every variation of an object, list every key. A cache key purge is the only type that reaches the Tiered Cache layer. +A cache key purge takes a list of cache keys. A key names one copy of an object. A cache key purge is the only type that reaches the Tiered Cache layer. + +With Advanced Cache Key, a Feature of [Application Accelerator](/en/documentation/platform/applications/application-accelerator/), a key can vary by query string, sorted or not, and by cookie, device group, or request method. Through [Image Processor](/en/documentation/platform/applications/image-processor/), a key can also vary by image format. To purge every copy of an object, list the key of each one. ### Wildcard purge -A wildcard purge takes one expression: `scheme://host` or `host`, with an optional `/path` and `?query-string`. The expression carries an asterisk (`*`) in the path or in the query string. Several asterisks match a more complex path. Each request carries one expression, and a wildcard purge reaches the Cache layer only, not Tiered Cache. The list below carries ten valid wildcard expressions: +A wildcard purge takes one expression: `scheme://host` or `host`, with an optional `/path` and `?query-string`. The expression carries an asterisk (`*`) in the path or in the query string. Several asterisks match a more complex path. Each request carries one expression, and a wildcard purge reaches the Cache layer only, not Tiered Cache. + +The list below carries ten valid wildcard expressions: - `www.example.com/*` - `static.example.com/include/*.css` @@ -93,27 +95,29 @@ A wildcard purge takes one expression: `scheme://host` or `host`, with an option ## Purge content that varies -When a cache setting varies the cache key, one object has one key per variation. The table names the purge that reaches each kind of variation. +When a cache setting varies the cache key, one object has one key per copy. The table names the purge that reaches each kind of variation. | Variation | How to purge | | --- | --- | -| Cookies | A cache key purge that lists every variation, or a wildcard purge with `@@*` at the end | -| Query string | A cache key purge that lists every variation, a wildcard purge with `?*` at the end, or a URL purge that names only the arguments in the key, in alphabetical order when `sort_enabled` is on | -| Device group | A cache key purge that lists every variation, or a wildcard purge with `@@*` at the end | -| Image Processor | A cache key purge that lists every variation, or a wildcard purge with `*` at the end | +| Cookies | A cache key purge that lists the key of every copy, or a wildcard purge with `@@*` at the end | +| Query string | A cache key purge that lists the key of every copy, a wildcard purge with `?*` at the end, or a URL purge that names only the arguments in the key, in alphabetical order when `sort_enabled` is on | +| Device group | A cache key purge that lists the key of every copy, or a wildcard purge with `@@*` at the end | +| Image Processor | A cache key purge that lists the key of every copy, or a wildcard purge with `*` at the end | | Large File Optimization | A cache key purge that lists every fragment's key, or a wildcard purge such as `static.example.com/media/file.mp4*` | -| Cached `POST` and `OPTIONS` | A cache key purge that lists every variation, or a wildcard purge with `@@*` at the end | +| Cached `POST` and `OPTIONS` | A cache key purge that lists the key of every copy, or a wildcard purge with `@@*` at the end | -Query-string, cookie, device group, and request method variation come from Advanced Cache Key, in [Application Accelerator](/en/documentation/platform/applications/application-accelerator/). Application Accelerator also caches `POST` and `OPTIONS` responses; without it, Azion caches `GET` and `HEAD` only. For the behaviors, refer to [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/). +Query-string, cookie, device group, and request method variation come from Advanced Cache Key, in [Application Accelerator](/en/documentation/platform/applications/application-accelerator/). Application Accelerator also caches `POST` and `OPTIONS` responses. Without it, Azion caches `GET` and `HEAD` only. For the behaviors, refer to [Application Accelerator settings](/en/documentation/platform/applications/application-accelerator/settings/). -An image that [Image Processor](/en/documentation/platform/applications/image-processor/) serves has one key per processing and per format when the cache setting names `ims` in its query-string allowlist. When the cache setting does not vary the key by query string, the `ims` value is not part of the key. Every size and processing of the path then shares a key, and the first one stored answers every `ims` value. With `ims` in the allowlist, the key carries the host and path, then `@@`, the `ims` query string, and the converted format at the end, with no separator. The four keys below belong to one image: +An image that [Image Processor](/en/documentation/platform/applications/image-processor/) serves has one key per processing and per format when the cache setting names the `ims` parameter in its query-string allowlist. When the cache setting does not vary the key by query string, the `ims` value is not part of the key. Every size and processing of the path then shares a key, and the first one stored answers every `ims` value. + +With `ims` in the allowlist, the key carries the host and path, then `@@`, the `ims` parameter, and the converted format at the end, with no separator. The four keys below belong to one image: - `httpstatic.example.com/static/images/image.jpg@@` - `httpstatic.example.com/static/images/image.jpg@@webp` - `httpstatic.example.com/static/images/image.jpg@@?ims=88x` - `httpstatic.example.com/static/images/image.jpg@@?ims=88xwebp` -With Large File Optimization on in the cache setting, Azion caches a large object in fragments, each with its own key. The file can stay in the cache after a purge of its URL. To purge it, list each fragment's key, or use the wildcard `static.example.com/media/file.mp4*`. That wildcard clears every fragment of one file. +With Large File Optimization on in the cache setting, Azion caches a large object in fragments, each with its own key. The file can stay in the cache after a purge of its URL, while the wildcard in the Large File Optimization row clears every fragment of one file. :::caution A purge of individual fragments can leave old and new fragments side by side. When the file changes at the origin, a fragment that was not purged stays in the cache next to the fragments fetched again. @@ -126,25 +130,39 @@ A purge of individual fragments can leave old and new fragments side by side. Wh The API reads the purge type from the path and the arguments from `items`. The request body below sends a URL purge through `POST /v4/workspace/purge/url`: ```json -{"items":["https://www.example.com/include/site.js"],"layer":"cache"} +{ + "items": ["https://www.example.com/include/site.js"], + "layer": "cache" +} ``` -A wildcard purge goes through `POST /v4/workspace/purge/wildcard`; without `layer`, the API purges `cache`: +A wildcard purge goes through `POST /v4/workspace/purge/wildcard`. Without `layer`, the API purges `cache`: ```json -{"items":["www.example.com/include/*.css"]} +{ + "items": ["www.example.com/include/*.css"] +} ``` A cache key purge goes through `POST /v4/workspace/purge/cachekey`: ```json -{"items":["httpswww.example.com/include/site.js"],"layer":"cache"} +{ + "items": ["httpswww.example.com/include/site.js"], + "layer": "cache" +} ``` Each request answers with HTTP `201`, `state` set to `executed`, and the items and the layer under `data`: ```json -{"state":"executed","data":{"items":[...],"layer":"cache"}} +{ + "state": "executed", + "data": { + "items": [...], + "layer": "cache" + } +} ``` The CLI sends the same three purges from the command line, the last one to the Tiered Cache layer: @@ -190,10 +208,11 @@ The bounds below apply to purge requests. Each row names the API's answer past t | Value | Bound | Past the bound | | --- | --- | --- | -| URL or cache key length | 4,096 characters | The API accepts a longer URL when it receives the request: a purge of one 4,098-character URL returns HTTP `201`. | | URL and cache key objects per request | 50 objects | HTTP `400`, error `10065` | | Wildcard expressions per request | 1 | HTTP `400`, error `10065` | +A URL or a cache key takes up to 4,096 characters. The API does not refuse a longer URL when it receives the request, and answers HTTP `201`. + Six more bounds set the rate of purge requests, the length of a wildcard, and how much purge history Azion keeps. | Value | Bound | diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/rules-engine.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/rules-engine.mdx index f82fb0cd6f..51c6bb2261 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/rules-engine.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/rules-engine.mdx @@ -10,7 +10,9 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Rules Engine for Applications is a Feature of Applications that holds the rules of an [Application](/en/documentation/platform/applications/). A rule is conditional logic that the Application applies to a request or to its response. For example, a rule can send the request to a [Connector](/en/documentation/platform/connectors/), apply a [cache setting](/en/documentation/platform/applications/cache/cache-settings/), or invoke a [Function Instance](/en/documentation/platform/applications/functions-instances/). Each rule has criteria, its _if_, and behaviors, its _then_. It runs its behaviors only when a request matches its criteria. Every rule belongs to one phase: the Request Phase acts on the request, and the Response Phase acts on the response. +Rules Engine for Applications is a Feature of Applications that holds the rules of an [Application](/en/documentation/platform/applications/). A rule is an entry in Rules Engine for Applications that runs its behaviors, in one phase, on the requests its criteria match. Each rule has criteria, its _if_, and behaviors, its _then_. The two phases are the Request Phase, which acts on the request, and the Response Phase, which acts on the response. + +For example, a rule can send the request to a [Connector](/en/documentation/platform/connectors/), apply a [cache setting](/en/documentation/platform/applications/cache/cache-settings/), or invoke a [Function Instance](/en/documentation/platform/applications/functions-instances/). The model matches path-based routing in a reverse proxy: each criterion is a match condition, each behavior is an action, and a Connector holds the address of the backend server. Some variables and behaviors need a Platform Resource turned on in the Application, and each table on this page names it. For the order in which an Application runs its rules and behaviors, refer to [How Applications works](/en/documentation/platform/applications/how-it-works/). @@ -20,7 +22,7 @@ When the deployment of a [Workload](/en/documentation/platform/workloads/) sets ## Rule fields -A new Application has no rules, and [Create request and response rules](/en/documentation/guides/application-development/getting-started/rules-engine/) shows how to create one in Azion Console. In the API, a rule is a JSON object: a request sets five of its fields, and the platform sets and returns the other five. For the fields you set, the Description column also names the label of each one in the rule form of Azion Console. +In the API, a rule has ten fields: a request sets five, and the platform sets and returns the other five. A new Application has no rules, and [Create request and response rules](/en/documentation/guides/application-development/getting-started/rules-engine/) shows how to create one in Azion Console. For the fields you set, the Description column also names the label of each one in the rule form of Azion Console. | Field | Type | Required | Description | | --- | --- | --- | --- | @@ -35,7 +37,9 @@ A new Application has no rules, and [Create request and response rules](/en/docu | `last_modified` | date-time | Read-only | When the rule last changed | | `created_at` | date-time | Read-only | When the rule was created | -The Console rule list does not show `id`, and `azion list rules-engine` prints it as `ID`. Give each rule a unique name. Past 1,000 characters of `description`, the Console shows `Description should not exceed 1000 characters`. +The Console rule list does not show `id`, and `azion list rules-engine` prints it as `ID`. + +Give each rule a unique name. Past 1,000 characters of `description`, the Console shows `Description should not exceed 1000 characters`. The platform assigns `order` as rules are created: the first rule of a phase carries `0`, and the next one carries `1`. The Console numbers the same positions from `1`, so the rule whose `order` is `0` is the one its list shows as `1`. The Console rule list lets you move a rule, and a position past the end of the list places the rule last. The API reorders a phase with one call, which the API section lists. @@ -43,7 +47,7 @@ The platform assigns `order` as rules are created: the first rule of a phase car ## Phases -You set the phase of a rule when you create it, and you cannot change it later. To run the same logic in the other phase, create a new rule there. In Azion Console, the rule list groups the rules by phase, and the API keeps each phase in its own collection. +A rule runs in the Request Phase or the Response Phase, which you set when you create the rule and cannot change. To run the same logic in the other phase, create a new rule there. In Azion Console, the rule list groups the rules by phase, and the API keeps each phase in its own collection. | Phase | What its rules act on | API collection | | --- | --- | --- | @@ -61,12 +65,23 @@ A criterion is a condition a request must meet: a variable, an operator, and, fo This criterion matches a request from a desktop browser, with a regular expression on the `User-Agent` header: ```json -[[{ "variable": "${http_user_agent}", "conditional": "if", "operator": "matches", "argument": "(Chrome|Mozilla)" }]] +[ + [ + { + "variable": "${http_user_agent}", + "conditional": "if", + "operator": "matches", + "argument": "(Chrome|Mozilla)" + } + ] +] ``` ### Variables -A variable is a value of the request or of the response, written `${name}`. The Phases column names where a criterion can read it. `${request_uri}` and `${device_group}` require [Application Accelerator](/en/documentation/platform/applications/application-accelerator/settings/) turned on in the Application. A rule that reads one of them in an Application with Application Accelerator off is refused. The API answers HTTP `400` with the error code `25047`, `Missing Required Modules`, and the Errors section carries the full body. `${uri}` needs no Platform Resource, so it is the URI variable for an Application without Application Accelerator. +A variable is a value of the request or of the response, written `${name}`. The Phases column names where a criterion can read it. + +`${request_uri}` and `${device_group}` require [Application Accelerator](/en/documentation/platform/applications/application-accelerator/settings/) turned on in the Application. A rule that reads one of them in an Application with Application Accelerator off is refused. The API answers HTTP `400` with the error code `25047`, `Missing Required Modules`, and the Errors section carries the full body. `${uri}` needs no Platform Resource, so it is the URI variable for an Application without Application Accelerator. Six rows name a pattern instead of a variable. In `${arg_name}`, `${cookie_name}`, `${http_name}`, `${sent_http_name}`, `${upstream_cookie_name}`, and `${upstream_http_name}`, replace `name` with the argument, cookie, or header to read. @@ -76,7 +91,7 @@ Six rows name a pattern instead of a variable. In `${arg_name}`, `${cookie_name} | `${args}` | Every argument name and value in the query string | `${args}` holds `search=test` for `/path?search=test` | Request, Response | | `${cookie_name}` | The value of the cookie `name`. Replace each hyphen in `name` with an underscore | `${cookie_icl_current_language}` holds `pt-br` for `icl_current_language = pt-br` | Request, Response | | `${device_group}` | The name of the [device group](/en/documentation/platform/applications/device-groups/) the request matches, among the device groups of the Application. Requires Application Accelerator | `Mobile` | Request, Response | -| `${domain}` | The host name or `Host` header of the request, as `${host}` reads it, without the last subdomain after the second-level domain | `blog.domain.com` for `az.blog.domain.com` | Request, Response | +| `${domain}` | The host name or `Host` header of the request, as `${host}` reads it, without the last subdomain after the second-level domain | `blog.example.com` for `az.blog.example.com` | Request, Response | | `${geoip_city}` | The city name | `Frankfurt am Main` | Request, Response | | `${geoip_city_continent_code}` | The two-letter continent code | `EU`, for Europe | Request, Response | | `${geoip_city_country_code}` | The two-letter country code | `IN`, for India | Request, Response | @@ -86,9 +101,9 @@ Six rows name a pattern instead of a variable. In `${arg_name}`, `${cookie_name} | `${geoip_country_name}` | The country name | `France` | Request, Response | | `${geoip_region}` | The two-letter region code | `FL`, for Florida | Request, Response | | `${geoip_region_name}` | The region name | `Ontario` | Request, Response | -| `${host}` | In order of precedence: the host name in the request line, the value of the `Host` header, or the name of the server that serves the request | `blog.domain.com` | Request, Response | +| `${host}` | In order of precedence: the host name in the request line, the value of the `Host` header, or the name of the server that serves the request | `blog.example.com` | Request, Response | | `${http_name}` | The value of the request header `name`. Write `name` in lowercase and replace each hyphen with an underscore. `name` must be a valid [HTTP request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) | `${http_accept}` holds `image/webp,image/apng` for `Accept: image/webp,image/apng` | Request, Response | -| `${remote_addr}` | The IP address of the client that sends the request | `200.10.2.50` | Request, Response | +| `${remote_addr}` | The IP address of the client that sends the request | `203.0.113.50` | Request, Response | | `${remote_port}` | The TCP source port of the client connection, which changes from one connection to the next | `6742` | Request, Response | | `${remote_user}` | The user name sent through basic authentication, when the request carries one | `username` | Request, Response | | `${request}` | The first line of the request as the client sent it: the method, the URI, and the HTTP version | `GET /path HTTP/2.0` | Request, Response | @@ -97,15 +112,15 @@ Six rows name a pattern instead of a variable. In `${arg_name}`, `${cookie_name} | `${request_uri}` | The complete URI of the request, query string included, with special UTF-8 characters URL encoded. Requires Application Accelerator | `/path?var=value%20of%20var` | Request, Response | | `${scheme}` | The scheme of the request | `https` | Request, Response | | `${sent_http_name}` | The value of the response header `name`. Write `name` in lowercase and replace each hyphen with an underscore | `${sent_http_content_length}` holds `9593` for `Content-Length: 9593` | Response | -| `${server_addr}` | The IP address of the server that receives the request | `200.0.0.0` | Request | +| `${server_addr}` | The IP address of the server that receives the request | `198.51.100.10` | Request | | `${server_port}` | The port of the server that receives the request | `8080` | Request | | `${status}` | The status code of the response | `200` | Response | | `${tcpinfo_rtt}` | The round-trip time (RTT) of the client's TCP connection, in microseconds | `24763` | Response | -| `${upstream_addr}` | The IP address and port of the origin that answered. Several origins are separated by commas. After an internal redirect from one group of servers to another, started by an `X-Accel-Redirect` or an error page, the groups are separated by a colon | `192.168.1.1:80, 192.168.1.2:80`, or `192.168.1.1:80, 192.168.1.2:80 : 192.168.10.1:80, 192.168.10.2:80` after a redirect | Response | +| `${upstream_addr}` | The IP address and port of the origin that answered. Several origins are separated by commas. After an internal redirect from one group of servers to another, started by an `X-Accel-Redirect` or an error page, the groups are separated by a colon | `192.0.2.1:80, 192.0.2.2:80`, or `192.0.2.1:80, 192.0.2.2:80 : 192.0.2.11:80, 192.0.2.12:80` after a redirect | Response | | `${upstream_cookie_name}` | The value of the cookie `name` that the origin sends in `Set-Cookie`. When several origins answer one request, only the cookies of the last one are kept | `${upstream_cookie_uuid}` holds `12345` for `Set-Cookie: uuid = 12345` | Response | | `${upstream_http_name}` | The value of the header `name` that the origin sends. Write `name` in lowercase and replace each hyphen with an underscore. When several origins answer one request, only the headers of the last one are kept | `${upstream_http_server}` holds `UploadServer` for `Server: UploadServer` | Response | | `${upstream_status}` | The status code the origin returns. Several origins are separated by commas, and the groups of an internal redirect by a colon, as in `${upstream_addr}` | `200, 201`, or `500, 502 : 200, 200` after a redirect | Response | -| `${uri}` | The normalized, URL-decoded URI of the request. The value can change while the request is processed, for example after an internal redirect or when an index file answers. For the query string or URL-encoded characters, read `${request_uri}` | `/path/my file.txt` | Request, Response | +| `${uri}` | The normalized, URL-decoded URI of the request, without its query string. The value can change while the request is processed, for example after an internal redirect or when an index file answers. For the query string or URL-encoded characters, read `${request_uri}` | `/path/my file.txt` | Request, Response | ### Mutual Transport Layer Security (mTLS) variables @@ -116,7 +131,7 @@ These variables hold the client certificate that a request presents over mTLS, w | `${ssl_client_cert}` | The client certificate in Privacy-Enhanced Mail (PEM) format. Deprecated: read `${ssl_client_escaped_cert}` instead | `-----BEGIN CERTIFICATE-----` `MIICnz...` `-----END CERTIFICATE-----` | | `${ssl_client_escaped_cert}` | The client certificate in PEM format, as a URL-encoded string | `-----BEGIN%20CERTIFICATE-----%0AMIICnz...%0A-----END%20CERTIFICATE-----` | | `${ssl_client_fingerprint}` | The Secure Hash Algorithm 1 (SHA-1) fingerprint of the client certificate | `2fd4e1c67a2d28fced849` | -| `${ssl_client_i_dn}` | The issuer Distinguished Name (DN) string of the client certificate | `/C=US/ST=California/L=San Francisco/O=Example CA/CN=issuer.com` | +| `${ssl_client_i_dn}` | The issuer Distinguished Name (DN) string of the client certificate | `/C=US/ST=California/L=San Francisco/O=Example CA/CN=issuer.example.com` | | `${ssl_client_s_dn}` | The subject DN string of the client certificate | `/C=US/ST=California/L=San Francisco/O=Example CA/CN=example.com` | | `${ssl_client_s_dn_parsed}` | The subject Common Name (CN) extracted from the client certificate, as a string | `example.com` | | `${ssl_client_serial}` | The serial number of the client certificate | `6C:0A:83:7E:92:3B:D6:C6:E3:56:50:E7` | @@ -135,19 +150,19 @@ This Response Phase rule sets a cookie that records the host of the request: | | Variable | Operator | Argument | | --- | --- | --- | --- | -| If | `${host}` | `is_equal` | `host.com` | +| If | `${host}` | `is_equal` | `example.com` | | | Behavior | Argument | | --- | --- | --- | | Then | _Add Response Cookie_ | `cookie-host-value=${host}` | -When the rule matches, the response carries `Set-Cookie: cookie-host-value=host.com`. +When the rule matches, the response carries `Set-Cookie: cookie-host-value=example.com`. Two more variables act as functions: each takes an argument, and both work only inside a behavior argument. | Variable | What it returns | Example | | --- | --- | --- | -| `${cookie_time_offset(number)}` | The current date plus an offset of `number` seconds, for the expiration of a cookie | `cookie-name=cookie-value; Expires=${cookie_time_offset(3600)}` in [Add Response Cookie](#add-request-cookie-and-add-response-cookie) makes the cookie expire 1 hour after it is created | +| `${cookie_time_offset(number)}` | The current date plus an offset of `number` seconds, for the expiration of a cookie | `cookie-name=cookie-value; Expires=${cookie_time_offset(3600)}` in [Add Response Cookie](/en/documentation/platform/applications/rules-engine/#add-request-cookie-and-add-response-cookie) makes the cookie expire 1 hour after it is created | | `${encode_base64(string)}` | `string`, encoded in base64 | `${encode_base64(http://www.yourdomain.com/)}` returns `aHR0cDovL3d3dy55b3VyZG9tYWluLmNvbS8=` | ### Operators @@ -198,7 +213,7 @@ The two API columns give the `type` each phase accepts, and Requires names the P | Deliver | `deliver` | `deliver` | None | | Deny (403 Forbidden) | `deny` | Not available | None | | Enable Gzip | `enable_gzip` | `enable_gzip` | None | -| Enforce HLS cache | Added by Azion | Not available | Live Ingest | +| Enforce HLS cache | Added by Azion | Not available | [Live Ingest](/en/documentation/platform/connectors/live-ingest/) | | Filter Request Cookie / Filter Response Cookie | `filter_request_cookie` | `filter_response_cookie` | Application Accelerator | | Filter Request Header / Filter Response Header | `filter_request_header` | `filter_response_header` | None | | Finish Request Phase | `finish_request_phase` | Not available | None | @@ -222,7 +237,7 @@ In the Response Phase, the argument can carry [Set-Cookie](https://developer.moz - `Expires=date`, in the format `EEE, d MMM yyyy HH:mm:ss Z` - `Domain=domain-value` - `Path=path-value` -- `Max-age=number`, a TTL in seconds that takes precedence over `Expires` +- `Max-age=number`, a time to live (TTL) in seconds that takes precedence over `Expires` - `SameSite=value; Secure` - `HttpOnly` @@ -288,7 +303,7 @@ _Enable Gzip_ compresses the content with gzip when the browser of the user supp ### Enforce HLS cache -_Enforce HLS cache_ imposes the cache policy Azion defines for live HLS transmissions, and requires Live Ingest. Azion adds the behavior to a Request Phase rule every time you select a Live Ingest source. The behavior does two things: it bypasses the cache rules of the Application, and it applies the live HLS policy. +_Enforce HLS cache_ imposes the cache policy Azion defines for live transmissions over HTTP Live Streaming (HLS), and requires Live Ingest. Azion adds the behavior to a Request Phase rule every time you select a Live Ingest source. The behavior does two things: it bypasses the cache rules of the Application, and it applies the live HLS policy. | Object | Cache time | | --- | --- | @@ -317,11 +332,15 @@ Five headers cannot be filtered or overwritten: ### Finish Request Phase -_Finish Request Phase_ ends the Request Phase. The behaviors after it in the rule, and the rules after that rule, do not run. It runs in the Request Phase, requires no Platform Resource, and is `{ "type": "finish_request_phase" }` in the API. Azion Console does not offer it in the behavior list: send it through the API, or from the same JSON with `azion create rules-engine` in Azion CLI. +_Finish Request Phase_ ends the Request Phase. The behaviors after it in the rule, and the rules after that rule, do not run. It runs in the Request Phase, requires no Platform Resource, and is `{ "type": "finish_request_phase" }` in the API. Azion Console does not offer it in the behavior list: send it through the API, or from a JSON file with `azion create rules-engine` in Azion CLI. ### Forward Cookies -_Forward Cookies_ makes Azion forward the `Set-Cookie` header that the origin returns to users, even when the response comes from cache. It runs in the Request Phase, requires Application Accelerator turned on in the Application, and is `{ "type": "forward_cookies" }` in the API. A cached response can then carry the `Set-Cookie` of another user's session. To keep sessions apart, refer to [Forward cookies from the origin to the user](/en/documentation/guides/application-performance/cache-and-purge/cache-settings/#forward-cookies-from-the-origin-to-the-user). +_Forward Cookies_ makes Azion forward the `Set-Cookie` header that the origin returns to users, even when the response comes from cache. It runs in the Request Phase, requires Application Accelerator turned on in the Application, and is `{ "type": "forward_cookies" }` in the API. + +:::caution +With Forward Cookies, a cached response can carry the `Set-Cookie` of another user's session. To keep sessions apart, refer to [Forward cookies from the origin to the user](/en/documentation/guides/application-performance/cache-and-purge/cache-settings/#forward-cookies-from-the-origin-to-the-user). +::: Azion does not filter the `Cookie` request header by default, whatever the Forward Cookies configuration, so the cookies a script sets with `document.cookie` reach the origin. @@ -368,11 +387,13 @@ In the API, `attributes.value` holds the ID of the Function Instance, not of the _Set Cache Policy_ applies a [cache setting](/en/documentation/platform/applications/cache/cache-settings/) to the requests the rule matches, which is how a cache setting reaches a request. It runs in the Request Phase and requires no other Platform Resource. The cache setting has to exist before a rule can apply it, and [Cache quickstart](/en/documentation/platform/applications/cache/quickstart/) creates a first cache setting and the rule that applies it. -The cache setting holds how long an object stays in cache. Its [Application Accelerator fields](/en/documentation/platform/applications/cache/cache-settings/#application-accelerator) hold the variations that set the cache key. In the API, `attributes.value` holds the ID of the cache setting. The API returns that ID as an integer, even when the request sends it as a string. A cache setting that a rule applies cannot be deleted: the API answers `400` with code `21014`. +The cache setting holds how long an object stays in cache. Its [Application Accelerator fields](/en/documentation/platform/applications/cache/cache-settings/#application-accelerator) hold the variations that set the cache key. + +In the API, `attributes.value` holds the ID of the cache setting. The API returns that ID as an integer, even when the request sends it as a string. A cache setting that a rule applies cannot be deleted: the API answers `400` with code `21014`. ### Set Connector -_Set Connector_ sends the requests the rule matches to a [Connector](/en/documentation/platform/connectors/), which routes them to the origin. It runs in the Request Phase and requires no Platform Resource, so a rule with `${uri}` and _Set Connector_ works in an Application without Application Accelerator. In the API, `attributes.value` holds the ID of the Connector, as the API section shows. +_Set Connector_ sends the requests the rule matches to a [Connector](/en/documentation/platform/connectors/), which holds the address of your origin and routes them to it. It runs in the Request Phase and requires no Platform Resource, so a rule with `${uri}` and _Set Connector_ works in an Application without Application Accelerator. In the API, `attributes.value` holds the ID of the Connector, as the API section shows. --- @@ -384,15 +405,15 @@ Every rule operation is authenticated and sits under `https://api.azion.com/v4/w | --- | --- | --- | | Create a rule | `POST /request_rules` | `POST /response_rules` | | List the rules of the phase | `GET /request_rules` | `GET /response_rules` | -| Retrieve a rule | `GET /request_rules/{request_rule_id}` | `GET /response_rules/{response_rule_id}` | -| Replace a rule | `PUT /request_rules/{request_rule_id}` | `PUT /response_rules/{response_rule_id}` | -| Update part of a rule | `PATCH /request_rules/{request_rule_id}` | `PATCH /response_rules/{response_rule_id}` | -| Delete a rule | `DELETE /request_rules/{request_rule_id}` | `DELETE /response_rules/{response_rule_id}` | +| Retrieve a rule | `GET /request_rules/` | `GET /response_rules/` | +| Replace a rule | `PUT /request_rules/` | `PUT /response_rules/` | +| Update part of a rule | `PATCH /request_rules/` | `PATCH /response_rules/` | +| Delete a rule | `DELETE /request_rules/` | `DELETE /response_rules/` | | Reorder the rules | `PUT /request_rules/order` | `PUT /response_rules/order` | A create answers `202` with a `state` of `pending`, and a list answers `200`. The reorder call takes an `order` array that lists the rule IDs of the phase in their new order. -This call creates a Request Phase rule that sends every request of the Application to a Connector: +Every path starts with `/`, so a criterion with `starts_with` and `/` matches every request. This call creates a Request Phase rule that sends every request of the Application to a Connector: ```bash curl --request POST \ @@ -403,8 +424,24 @@ curl --request POST \ --data '{ "name": "send-to-connector", "active": true, - "criteria": [[{ "variable": "${uri}", "conditional": "if", "operator": "starts_with", "argument": "/" }]], - "behaviors": [{ "type": "set_connector", "attributes": { "value": } }] + "criteria": [ + [ + { + "variable": "${uri}", + "conditional": "if", + "operator": "starts_with", + "argument": "/" + } + ] + ], + "behaviors": [ + { + "type": "set_connector", + "attributes": { + "value": + } + } + ] }' ``` @@ -414,13 +451,15 @@ The response carries `202` and a `state` of `pending`. The excerpt keeps the rul {"state":"pending","data":{"id":,"name":"send-to-connector","active":true,"criteria":[[{"conditional":"if","variable":"${uri}","operator":"starts_with","argument":"/"}]],"behaviors":[{"type":"set_connector","attributes":{"value":}}],"description":"","order":0,…}} ``` -The platform adds `description`, an empty string when the create sends none, and `order`, the position of the rule in its phase. The same body with `${request_uri}` in place of `${uri}` fails with code `25047` in an Application without Application Accelerator. +The platform adds `description`, an empty string when the create sends none, and `order`, the position of the rule in its phase. The same body with `${request_uri}` in place of `${uri}` fails with code `25047` in an Application without Application Accelerator. [Applications quickstart](/en/documentation/platform/applications/quickstart/) builds the same rule in Azion Console. --- ## CLI -[Azion CLI](/en/documentation/devtools/cli/) creates a rule with `azion create rules-engine`, which reads the rule from a JSON file in the shape the API takes. `--phase` names the phase, and `azion create rules-engine` has no default for it: in a terminal, the command asks for the phase, and with no terminal it fails with `Error: Failed to parse your response.` +[Azion CLI](/en/documentation/devtools/cli/) creates a rule with `azion create rules-engine`, which reads the rule from a JSON file in the shape the API takes. + +The `--phase` flag names the phase, and `azion create rules-engine` has no default for it: in a terminal, the command asks for the phase, and with no terminal it fails with `Error: Failed to parse your response.` This file applies a cache setting to every request whose path starts with `/static/`: @@ -429,8 +468,24 @@ This file applies a cache setting to every request whose path starts with `/stat "name": "apply-static-assets-cache", "description": "Applies the static-assets cache setting to /static/", "active": true, - "criteria": [[{ "variable": "${uri}", "operator": "starts_with", "conditional": "if", "argument": "/static/" }]], - "behaviors": [{ "type": "set_cache_policy", "attributes": { "value": } }] + "criteria": [ + [ + { + "variable": "${uri}", + "operator": "starts_with", + "conditional": "if", + "argument": "/static/" + } + ] + ], + "behaviors": [ + { + "type": "set_cache_policy", + "attributes": { + "value": + } + } + ] } ``` diff --git a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/websocket.mdx b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/websocket.mdx index 44b6e7de7b..ed7ea62c3c 100644 --- a/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/websocket.mdx +++ b/apps/docs/src/content/docs/en/pages/main-menu/reference/build/edge-application/websocket.mdx @@ -10,7 +10,9 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -WebSocket is a protocol, specified in [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455), that keeps one TCP connection open in both directions between a client and a server. After one handshake, both sides exchange data over it in real time. **WebSocket Proxy** is a Feature of Applications that carries that connection between your users and your origin. The connection passes through an [Application](/en/documentation/platform/applications/) that acts as a reverse proxy for that origin. Use WebSocket Proxy for real-time applications such as online games, chat, notifications, and live streaming. +WebSocket is a protocol, specified in [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455), that keeps one TCP connection open in both directions between a client and a server. After one handshake, both sides exchange data over it in real time. + +**WebSocket Proxy** is a Feature of Applications that carries that connection between your users and your origin. The connection passes through an [Application](/en/documentation/platform/applications/) that acts as a reverse proxy for that origin. Use WebSocket Proxy for real-time applications such as online games, chat, notifications, and live streaming. WebSocket Proxy fits when the WebSocket server is your origin, because the Application only carries the connection to it. When a [Function](/en/documentation/platform/functions/) should act as the WebSocket server or client itself, use the [WebSocket API](/en/documentation/devtools/runtime/api-reference/websocket/) instead, which handles a server-side upgrade with `upgradeWebSocket()`. @@ -47,8 +49,6 @@ A WebSocket connection through an Application completes with `101 Switching Prot | --- | --- | --- | | Any status other than `101` | The client, the Application, or the origin did not complete the WebSocket connection | Check the client, the origin, and the [upgrade headers](/en/documentation/platform/applications/websocket/#upgrade-headers) | -The client and the origin both need native WebSocket support, and the request needs both upgrade headers with their values. - --- ## Limits diff --git a/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/como-funciona.mdx b/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/como-funciona.mdx index 5011768db4..9a78deefd7 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/como-funciona.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/como-funciona.mdx @@ -9,9 +9,11 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Quando a resposta de uma URL depende de um cookie, de um dispositivo ou do corpo de uma requisição, o cache precisa distinguir essas requisições. Em uma [Application](/pt-br/documentacao/plataforma/applications/), acrescentar essas entradas à cache key exige [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/), um recurso da plataforma que libera quatro capacidades para o cache e para as regras. Application Accelerator vem desativado em uma Application nova, e cada Application o ativa separadamente, no campo `modules.application_accelerator.enabled` da Application na API. Cada [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) da Application guarda por quanto tempo uma resposta fica em cache. Ele define então as entradas que tornam duas requisições diferentes, no seu próprio objeto `modules.application_accelerator`. Como uma variação altera a cache key, com o diagrama correspondente, está na [visão geral do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/#caminho-da-requisicao). +Quando a resposta de uma URL depende de um cookie, de um dispositivo ou do corpo de uma requisição, o cache precisa distinguir essas requisições. Em uma [Application](/pt-br/documentacao/plataforma/applications/), acrescentar essas entradas à cache key exige [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/), um recurso da plataforma que libera quatro capacidades para o cache e para as regras. Application Accelerator vem desativado em uma Application nova, e cada Application o ativa separadamente, no campo `modules.application_accelerator.enabled` da Application na API. -As seções cobrem o que ativar Application Accelerator libera, o que uma variação custa e como os purges alcançam as variações. A última seção compara _Bypass Cache_ com um tempo de vida (TTL) de 0. +Um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/), o conjunto de valores que diz ao Cache como e por quanto tempo armazenar e servir uma resposta, também guarda as entradas que tornam duas requisições diferentes, no seu próprio objeto `modules.application_accelerator`. Como uma variação altera a cache key, com o diagrama correspondente, está na [visão geral do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/#caminho-da-requisicao). + +As seções cobrem o que ativar Application Accelerator libera, o que uma variação custa e como os purges alcançam as cópias que as variações criam. A última seção compara _Bypass Cache_ com um tempo de vida (TTL) de 0. --- @@ -21,12 +23,14 @@ Ativar Application Accelerator libera quatro capacidades que parecem não ter re - Variação de cache por query string, por cookie, por device group e por método de requisição, por meio da [Advanced Cache Key](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#application-accelerator), uma feature de Application Accelerator. - Cache de respostas `POST` e `OPTIONS`, além das respostas `GET` e `HEAD` que uma Application armazena em cache sem ele. -- Um Max Age que pode chegar a 0 segundos, no campo `modules.cache.max_age` de um cache setting, menor que o piso de 60 segundos que vale sem ele. +- Um Max Age abaixo do piso de 60 segundos, no campo `modules.cache.max_age` de um cache setting. - Mais behaviors do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) e as variáveis `${request_uri}` e `${device_group}` nos critérios das regras. Os behaviors são _Add Request Cookie_ e _Add Response Cookie_, _Bypass Cache_, _Capture Match Groups_, _Filter Request Cookie_ e _Filter Response Cookie_, _Forward Cookies_ e _Rewrite Request_. -O que as quatro têm em comum é o conteúdo dinâmico. A variação de cache dá à cache key a entrada extra de que ela precisa para distinguir duas respostas corretas. O cache de respostas `POST` e `OPTIONS` estende o cache além de `GET` e `HEAD`, e um `POST` carrega essa entrada no corpo da requisição. Um TTL menor que um minuto serve ao conteúdo que deixa de ser correto antes de um minuto passar. Vários dos behaviors liberados agem justamente sobre os cookies e os paths que carregam a diferença. +O que as quatro têm em comum é o conteúdo dinâmico. A variação de cache dá à cache key a entrada extra de que ela precisa para distinguir duas respostas corretas. O cache de respostas `POST` e `OPTIONS` estende o cache além de `GET` e `HEAD`, e um `POST` carrega essa entrada no corpo da requisição. + +Um TTL menor que um minuto serve ao conteúdo que deixa de ser correto antes de um minuto passar. Vários dos behaviors liberados agem justamente sobre os cookies e os paths que carregam a diferença. -Application Accelerator entrega as quatro capacidades ou nenhuma. Uma Application recebe a variação de cache só junto com as outras três capacidades. A API recusa um cache setting que define uma variação em uma Application com Application Accelerator desativado. Para o erro que a API retorna, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros). +Application Accelerator entrega as quatro capacidades ou nenhuma. A API recusa um cache setting que define uma variação em uma Application com Application Accelerator desativado. Para o erro que a API retorna, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros). Ativar Application Accelerator mantém o tráfego como estava: os controles de query string, de cookie e de dispositivo de um cache setting começam em `ignore`, e a lista de métodos começa vazia. Um cache setting só alcança uma requisição quando um behavior [Set Cache Policy](/pt-br/documentacao/plataforma/applications/rules-engine/#set-cache-policy) aplica esse cache setting. @@ -36,33 +40,41 @@ Ativar Application Accelerator pode gerar custos relacionados ao uso. Para mais ## O custo de uma variação -A variação de cache custa primeiro em armazenamento. O custo decorre de como a key é montada: cada valor distinto de um atributo que varia produz um objeto em cache separado. Isso torna a escolha do atributo pelo qual variar mais consequente do que a decisão de variar. Um cookie cujo valor é único para cada visitante dá a cada visitante uma cópia do objeto. O cache ainda funciona, mas cada resposta armazenada passa a servir um único visitante. O número de objetos cresce com a audiência, e não com o conteúdo. +A variação de cache custa primeiro em armazenamento. O custo decorre de como a key é montada: cada valor distinto de um atributo que varia produz uma cópia separada da resposta. Isso torna a escolha do atributo pelo qual variar mais consequente do que a decisão de variar. + +Um cookie cujo valor é único para cada visitante dá a cada visitante uma cópia da resposta. O cache ainda funciona, mas cada cópia armazenada passa a servir um único visitante. O número de cópias cresce com a audiência, e não com o conteúdo. + +Uma allowlist é o controle desse custo. O behavior `allowlist` nomeia os argumentos de query string ou os cookies que alteram a resposta, então só um atributo que ele nomeia pode criar outra cópia. O behavior `all` varia por todo argumento de query string ou cookie que a requisição carrega. + +Por exemplo, um link que chega com um argumento de campanha ganha uma cópia separada sob `all`. Sob uma allowlist que não nomeia esse argumento, o mesmo link aponta para a cópia compartilhada. + +A ordenação aplica a mesma economia à ordem dos argumentos. Os argumentos escolhidos entram na key na ordem em que a requisição os enviou, então `?a=1&b=2` e `?b=2&a=1` são duas cópias de uma única resposta. Com `sort_enabled` ativo, toda ordem dos argumentos se agrupa sob uma única key, em ordem alfabética. -Uma allowlist é o controle desse custo. O behavior `allowlist` nomeia os argumentos de query string ou os cookies que alteram a resposta, então só um atributo que ele nomeia pode criar outro objeto. O behavior `all` varia por todo argumento de query string ou cookie que a requisição carrega. Por exemplo, um link que chega com um argumento de campanha ganha o próprio objeto em cache sob `all`. Sob uma allowlist que não nomeia esse argumento, o mesmo link aponta para o objeto compartilhado. +Por exemplo, uma listagem de produtos que muda com os argumentos `category` e `page` nomeia os dois em uma allowlist. Com `sort_enabled` ativo, toda ordem dos dois argumentos chega a uma única cópia. -A ordenação aplica a mesma economia à ordem dos argumentos. Os argumentos escolhidos entram na key na ordem em que a requisição os enviou, então `?a=1&b=2` e `?b=2&a=1` são dois objetos que guardam uma única resposta. Com `sort_enabled` ativo, essas variações se agrupam sob uma única key, em ordem alfabética. Por exemplo, uma listagem de produtos que muda com os argumentos `category` e `page` nomeia os dois em uma allowlist. Com `sort_enabled` ativo, toda ordem dos dois argumentos chega a um único objeto. O custo da ordenação é que a key passa a diferir da URL como o cliente a escreveu, o que importa na hora do purge. Para os passos no Console que definem esses controles, consulte [Configure a Advanced Cache Key para uma aplicação](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/advanced-cache-key/). +O custo da ordenação é que a key passa a diferir da URL como o cliente a escreveu, o que importa na hora do purge. Para os passos no Console que definem esses controles, consulte [Configure a Advanced Cache Key para uma aplicação](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/advanced-cache-key/). --- ## Variação de cache e purges -Um purge é uma requisição que remove um objeto do cache e encontra esse objeto pela sua cache key. Um purge por URL converte a URL que recebe em uma cache key sem considerar a variação de conteúdo. Então toda variação que a URL não carrega sobrevive a ele, como uma variação por cookie ou por device group, e as cópias dela permanecem no cache. +Um purge é uma requisição que remove um objeto do cache e encontra esse objeto pela sua cache key. Um purge por URL converte a URL que recebe em uma cache key sem considerar a variação de conteúdo. Então as cópias que uma variação por cookie ou por device group cria sobrevivem a ele, porque a URL não carrega essas entradas. -Dois tipos de purge alcançam essas cópias. Um purge por cache key nomeia cada variação, e um purge por wildcard termina a key com `@@*`. As variações por query string são a exceção, porque a query string faz parte da URL. Um purge por URL alcança essas variações quando os argumentos são enviados na ordem em que foram apresentados, ou em ordem alfabética quando `sort_enabled` está ativo. +Dois tipos de purge alcançam essas cópias. Um purge por cache key nomeia a key de cada cópia, e um purge por wildcard termina a key com `@@*`. As variações por query string são a exceção, porque a query string faz parte da URL. Um purge por URL alcança as cópias delas quando os argumentos são enviados na ordem em que foram apresentados, ou em ordem alfabética quando `sort_enabled` está ativo. -As variações que você configura são também os objetos que um purge precisa alcançar. Então uma variação com muitos valores distintos custa tanto na hora do purge quanto em armazenamento. Para os tipos de purge e os passos para executar cada um, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purgue-conteudo-que-varia). +Cada cópia que uma variação cria é também um objeto que um purge precisa alcançar. Então uma variação com muitos valores distintos custa tanto na hora do purge quanto em armazenamento. Para os tipos de purge e os passos para executar cada um, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purgue-conteudo-que-varia). --- ## Bypass Cache e um TTL de 0 -Sem Application Accelerator, o Max Age mais curto que um cache setting aceita, no seu campo `modules.cache.max_age`, é de 60 segundos, e a API recusa um valor menor. Para o erro, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros). Application Accelerator remove esse piso e permite 0 segundos, ou 3 segundos quando o cache setting também tem [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) ativo. Um TTL de 0 difere de não armazenar em cache, e essa diferença é a razão de ambos existirem. Os dois precisam de Application Accelerator, porque _Bypass Cache_ é um dos behaviors que ele libera. +Sem Application Accelerator, o campo `modules.cache.max_age` de um cache setting não aceita valor abaixo de 60 segundos. Para o erro que a API retorna, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros). Application Accelerator remove esse piso e permite 0 segundos, ou 3 segundos quando o cache setting também tem [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) ativo. -O behavior [Bypass Cache](/pt-br/documentacao/plataforma/applications/rules-engine/#bypass-cache) envia à origem cada requisição HTTP e HTTPS que corresponde à sua regra, e a resposta contorna o próprio cache da Azion. Ele deixa o browser cache como um behavior _Set Cache Policy_ o define. O efeito dele também para no próprio cache da Azion: uma Application com cache settings de Tiered Cache ativos continua a armazenar objetos em cache na camada do Tiered Cache pelo Max Age do cache setting. Use-o quando cada requisição precisa receber conteúdo diferente. +Um TTL de 0 difere de não armazenar em cache, e essa diferença é a razão de ambos existirem. Os dois precisam de Application Accelerator, porque _Bypass Cache_ é um dos behaviors que ele libera. -Um Max Age de 0 segundos mantém a requisição no caminho do cache: a resposta carrega uma cache key e informa `MISS`, e toda requisição ainda chega à origem. +O behavior [Bypass Cache](/pt-br/documentacao/plataforma/applications/rules-engine/#bypass-cache) envia à origem cada requisição HTTP e HTTPS que corresponde à sua regra, e a resposta contorna o próprio cache da Azion. Ele deixa o cache do navegador como um behavior _Set Cache Policy_ o define. O efeito dele também para no próprio cache da Azion: uma Application com cache settings de Tiered Cache ativos continua a armazenar objetos em cache na camada do Tiered Cache pelo Max Age do cache setting. Use-o quando cada requisição precisa receber conteúdo diferente. -Os dois enviam toda requisição à origem. A diferença é o caminho do cache: um TTL de 0 mantém a requisição nele, e _Bypass Cache_ mantém a resposta fora do cache da Azion. +Um Max Age de 0 segundos também envia toda requisição à origem, mas mantém a requisição no caminho do cache: a resposta carrega uma cache key e informa `MISS`. _Bypass Cache_, no lugar disso, mantém a resposta fora do cache da Azion. --- @@ -70,7 +82,7 @@ Os dois enviam toda requisição à origem. A diferença é o caminho do cache: - Os controles por trás da variação de cache, das respostas POST e OPTIONS em cache e de um TTL menor que o piso. + Os controles por trás da variação de cache, das respostas POST e OPTIONS em cache e de um TTL menor que o piso de 60 segundos. Os passos no Console que definem os controles de variação de um cache setting, incluindo Sort. Os passos que ativam o cache para respostas de POST e OPTIONS. Application Accelerator ativado e um primeiro cache setting que varia. diff --git a/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/configuracoes.mdx b/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/configuracoes.mdx index 3ff59295a4..403e2d34b5 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/configuracoes.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/configuracoes.mdx @@ -11,7 +11,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -[Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) é um recurso da plataforma que libera quatro capacidades para o cache e para as regras de uma [Application](/pt-br/documentacao/plataforma/applications/). As capacidades são a variação de cache, o cache de respostas `POST` e `OPTIONS`, um Max Age abaixo de 60 segundos e os behaviors e as variáveis do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) que esta página lista. Cada Application ativa Application Accelerator separadamente. Esta página traz o nome, o tipo e o padrão de cada campo, e a interface que o define. +[Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) é um recurso da plataforma que libera quatro capacidades para o cache e para as regras de uma [Application](/pt-br/documentacao/plataforma/applications/). As capacidades são a variação de cache, o cache de respostas `POST` e `OPTIONS`, um Max Age abaixo de 60 segundos e os behaviors e as variáveis do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) que esta página lista. Cada Application ativa Application Accelerator separadamente. --- @@ -27,9 +27,21 @@ Application Accelerator vem desativado em uma Application nova, e a configuraç | [`azion.config.js`](/pt-br/documentacao/devtools/cli/azion-config-js/) | O objeto `AzionApplication` | `applicationAcceleratorEnabled` | | [Azion Lib](/pt-br/documentacao/devtools/azion-lib/application/) | Os dados da atualização de uma Application, porque API v3 recusa o campo na criação | `application_acceleration` | -`modules.application_accelerator.enabled` é um booleano e assume `false` por padrão. `applicationAcceleratorEnabled` e `application_acceleration` são booleanos, e a flag da Azion CLI recebe uma string. +`modules.application_accelerator.enabled` é um booleano e assume `false` por padrão. `applicationAcceleratorEnabled` e `application_acceleration` são booleanos, e a flag da Azion CLI recebe uma string. Na API v4, este corpo em `PATCH /v4/workspace/applications/{id}` o ativa: -O [Azion Terraform Provider](/pt-br/documentacao/devtools/terraform/) gerencia o recurso da Application que carrega o switch. Ativar Application Accelerator pode gerar custos relacionados ao uso. Para mais informações, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#application-accelerator). +```json +{ + "modules": { + "application_accelerator": { + "enabled": true + } + } +} +``` + +O [Azion Terraform Provider](/pt-br/documentacao/devtools/terraform/) gerencia o recurso da Application que carrega o switch. + +Ativar Application Accelerator pode gerar custos relacionados ao uso. Para mais informações, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#application-accelerator). --- @@ -37,7 +49,7 @@ O [Azion Terraform Provider](/pt-br/documentacao/devtools/terraform/) gerencia o Todo cache setting carrega o seu próprio objeto `modules.application_accelerator`, que tem o mesmo nome do objeto da Application. O objeto da Application guarda só `enabled`, e o objeto do cache setting guarda as variações. Com Application Accelerator ativo na Application, os campos do objeto do cache setting podem sair do padrão. -Esses campos configuram a Advanced Cache Key, uma feature de Application Accelerator. Eles decidem quais partes de uma requisição, além do scheme, do host e do path, produzem um objeto separado em cache. Uma variação por cookie, por device group ou de `POST` em cache acrescenta o separador `@@` à cache key, assim como uma variação por query string sob `allowlist` ou `denylist`, na forma `@@?` e os seus argumentos. Sob `all`, a query string inteira vem depois do path, antes de `@@`. Uma resposta `OPTIONS` em cache acrescenta só o prefixo `options`, sem `@@`. Para o formato de uma cache key, consulte [Formato da cache key](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#formato-da-key). +Esses campos configuram a Advanced Cache Key, uma feature de Application Accelerator. Eles decidem quais partes de uma requisição, além do scheme, do host e do path, produzem uma cópia separada em cache. Para o marcador que cada variação acrescenta à cache key, consulte [Formato da cache key](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#formato-da-key). Cada campo corresponde a um controle da seção **Application Accelerator** de um cache setting, no Azion Console, que mostra essa seção só enquanto Application Accelerator está ativo na Application: @@ -46,7 +58,7 @@ Cada campo corresponde a um controle da seção **Application Accelerator** de u | `cache_vary_by_method` | array de enum, no máximo 2 valores: `options`, `post` | `[]` | **Cache vary by Method**, um checkbox por método | Os métodos de requisição cujas respostas são armazenadas em cache. | | `cache_vary_by_querystring.behavior` | enum: `ignore`, `all`, `allowlist`, `denylist` | `ignore` | **Cache vary by Query String** > **Behavior** | O modo que decide como a query string varia a cache key. | | `cache_vary_by_querystring.fields` | array de string | `[]` | **Cache vary by Query String** > **Fields** | Os argumentos de query string aos quais o modo se aplica. | -| `cache_vary_by_querystring.sort_enabled` | booleano | `false` | **Cache vary by Query String** > **Sort** | Se as variações se agrupam sob uma única cache key, em ordem alfabética. | +| `cache_vary_by_querystring.sort_enabled` | booleano | `false` | **Cache vary by Query String** > **Sort** | Se toda ordem dos argumentos se agrupa sob uma única cache key, em ordem alfabética. | | `cache_vary_by_cookies.behavior` | enum: `ignore`, `all`, `allowlist`, `denylist` | `ignore` | **Cache vary by Cookies** > **Behavior** | O modo que decide como os cookies variam a cache key. | | `cache_vary_by_cookies.cookie_names` | array de string | `[]` | **Cache vary by Cookies** > **Fields** | Os cookies aos quais o modo se aplica. | | `cache_vary_by_devices.behavior` | enum: `ignore`, `allowlist` | `ignore` | **Cache vary by Devices** > **Behavior** | O modo que decide como os device groups variam a cache key. | @@ -54,15 +66,41 @@ Cada campo corresponde a um controle da seção **Application Accelerator** de u No Azion Console, os dropdowns **Behavior** de **Cache vary by Query String** e de **Cache vary by Cookies** mostram _Allowlist_, _Denylist_, _Ignore_ e _All_. O de **Cache vary by Devices** mostra _Allowlist_ e _Ignore_. -`allowlist` e `denylist` na query string exigem pelo menos um argumento em `fields`, ou a API retorna o erro `21018`. Enquanto Application Accelerator está desativado na Application, a API recusa uma variação com o erro `21013`. Para todos os erros que um cache setting retorna, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros). +Só esses quatro controles definem as entradas que variam a key, então um header da requisição como `Accept-Language` não a varia. + +`allowlist` e `denylist` na query string exigem pelo menos um argumento em `fields`, ou a API retorna o erro `21018`. Enquanto Application Accelerator está desativado na Application, a API recusa com o erro `21013` um cache setting que varia o cache: um `behavior` de query string, de cookie ou de device group diferente de `ignore`, ou um método em `cache_vary_by_method`. Para todos os erros que um cache setting retorna, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros). + +Este cache setting mantém uma listagem de produtos por 30 segundos e dá a cada valor do argumento `category` uma cópia separada. Envie-o como corpo de `POST /v4/workspace/applications/{application_id}/cache_settings`: + +```json +{ + "name": "product-listing", + "browser_cache": { "behavior": "honor" }, + "modules": { + "cache": { + "behavior": "override", + "max_age": 30 + }, + "application_accelerator": { + "cache_vary_by_querystring": { + "behavior": "allowlist", + "fields": ["category"], + "sort_enabled": true + } + } + } +} +``` + +Um controle que o corpo deixa de fora mantém o seu padrão, `ignore`, ou uma lista vazia para os métodos. Um campo do mesmo cache setting fica fora desse objeto e ainda assim exige Application Accelerator: | Campo | Tipo | Padrão | Controle no Console | O que define | | --- | --- | --- | --- | --- | -| `modules.cache.max_age` | inteiro, de `0` a `31536000` segundos | `60` | **Cache** > **Max Age** | Por quanto tempo o cache guarda o objeto. Abaixo de 60, exige Application Accelerator. | +| `modules.cache.max_age` | inteiro, de `0` a `31536000` segundos | `60` | **Cache** > **Max Age** | Por quanto tempo o cache guarda o objeto. Abaixo de 60 segundos, exige Application Accelerator. | -Sem Application Accelerator, um `max_age` abaixo de 60 retorna o erro `21021`. Com Application Accelerator e Tiered Cache ativos, um valor abaixo de 3 retorna o erro `21020`. +Sem Application Accelerator, um `max_age` abaixo de 60 segundos retorna o erro `21021`. Com Application Accelerator e Tiered Cache ativos, um valor abaixo de 3 segundos retorna o erro `21020`. Para os tetos que limitam um cache setting, consulte [Limites](/pt-br/documentacao/plataforma/applications/limites/#application-accelerator). @@ -110,13 +148,13 @@ Estes behaviors do Rules Engine exigem Application Accelerator na Application qu | Behavior | Fases | O que faz | | --- | --- | --- | | [Add Request Cookie, Add Response Cookie](/pt-br/documentacao/plataforma/applications/rules-engine/#add-request-cookie-e-add-response-cookie) | Request, Response | Adiciona um cookie ao header `Set-Cookie`. | -| [Bypass Cache](/pt-br/documentacao/plataforma/applications/rules-engine/#bypass-cache) | Request | Impede que o cache da Azion guarde a resposta da origem e não altera o cache do navegador. | -| [Capture Match Groups](/pt-br/documentacao/plataforma/applications/rules-engine/#capture-match-groups) | Request, Response | Guarda em uma variável temporária a captura de uma expressão regular sobre um campo da requisição. | +| [Bypass Cache](/pt-br/documentacao/plataforma/applications/rules-engine/#bypass-cache) | Request | Envia a requisição à origem e mantém a resposta fora do cache da Azion. | +| [Capture Match Groups](/pt-br/documentacao/plataforma/applications/rules-engine/#capture-match-groups) | Request, Response | Guarda em um array temporário os grupos que uma expressão regular captura de um campo da requisição. | | [Filter Request Cookie, Filter Response Cookie](/pt-br/documentacao/plataforma/applications/rules-engine/#filter-request-cookie) | Request, Response | Remove um cookie da requisição à origem ou da resposta ao usuário. | | [Forward Cookies](/pt-br/documentacao/plataforma/applications/rules-engine/#forward-cookies) | Request | Encaminha o header `Set-Cookie` da origem aos usuários, inclusive em um cache hit. | | [Rewrite Request](/pt-br/documentacao/plataforma/applications/rules-engine/#rewrite-request) | Request | Altera o caminho do recurso requisitado à origem. | -_Bypass Cache_ age sobre o cache da Azion e não sobre a camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/). Uma Application cujos cache settings têm Tiered Cache ativo continua a armazenar objetos nessa camada pelo Max Age do cache setting. +_Bypass Cache_ não altera o cache do navegador. Ele age sobre o cache da Azion e não sobre a camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/). Uma Application cujos cache settings têm Tiered Cache ativo continua a armazenar objetos nessa camada pelo Max Age do cache setting. Os critérios de uma regra podem ler `${request_uri}` e `${device_group}`, e os dois exigem Application Accelerator. Uma regra que lê `${request_uri}` sem ele é recusada com `25047`. Para as variáveis, consulte [Variáveis](/pt-br/documentacao/plataforma/applications/rules-engine/#variaveis), e para os grupos aos quais `${device_group}` corresponde, consulte [Device Groups](/pt-br/documentacao/plataforma/applications/device-groups/). @@ -130,7 +168,7 @@ Os critérios de uma regra podem ler `${request_uri}` e `${device_group}`, e os - Como cada um desses campos altera a cache key, e quanto custa uma variação. + O que Application Accelerator libera, quanto custa uma variação e como um purge alcança as cópias dela. Ative Application Accelerator e crie um cache setting que varia a cache key. Os tetos que limitam os valores destas tabelas. Como purgar um objeto que varia por cookie, query string ou device group. diff --git a/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/primeiros-passos.mdx b/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/primeiros-passos.mdx index e91f2eb371..b2db8fdac0 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/primeiros-passos.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/primeiros-passos.mdx @@ -18,14 +18,14 @@ Este guia conduz você pelo seu primeiro cache setting que varia a cache key. O - Ativar [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) em uma Application. - Criar um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) que mantém a listagem por 30 segundos e varia pelo argumento `category`. -- Adicionar uma regra do Rules Engine que aplica o cache setting às requisições para `/products`. +- Adicionar uma regra do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) que aplica o cache setting às requisições para `/products`. - Requisitar a listagem duas vezes, com dois valores de `category`, e ler a cache key de cada resposta. Três partes da Application produzem esse resultado, e cada uma depende da anterior: -1. Application Accelerator fica ativo ou desativado em cada Application separadamente. Ele libera os campos que variam a cache key e remove o piso de 60 segundos do cache TTL. +1. Application Accelerator fica ativo ou desativado em cada Application separadamente. Ele libera os campos que variam a cache key e remove o piso de 60 segundos do Max Age, o tempo de vida (TTL) do cache. 2. Um cache setting pertence à Application e guarda o behavior de cache, o Max Age e a variação. Ele define o que o cache faz, não a quais requisições ele faz isso. -3. A regra do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) aplica o cache setting com o behavior [Set Cache Policy](/pt-br/documentacao/plataforma/applications/rules-engine/#set-cache-policy). Os critérios dela decidem quais requisições o cache setting cobre. +3. A regra do Rules Engine aplica o cache setting com o behavior [Set Cache Policy](/pt-br/documentacao/plataforma/applications/rules-engine/#set-cache-policy). Os critérios dela decidem quais requisições o cache setting cobre. Um cache setting só alcança uma requisição quando uma regra aplica esse cache setting, então criar um mantém o tráfego como estava. @@ -45,9 +45,9 @@ Um cache setting só alcança uma requisição quando uma regra aplica esse cach ### Console - Uma conta Azion. Para criar uma, consulte [Como criar uma conta na Azion](/pt-br/documentacao/fundamentos/criar-uma-conta/). -- A permissão **Edit Applications** na conta. Ela concede permissão para editar, criar e remover Applications, e também requer a permissão **View Applications**. Consulte [Permissões de equipes](/pt-br/documentacao/fundamentos/teams-permissions/). +- A permissão **Edit Applications** na conta. Ela concede permissão para editar, criar e remover Applications, e também requer a permissão **View Applications**. Para mais informações, consulte [Permissões de equipes](/pt-br/documentacao/fundamentos/teams-permissions/). - Uma Application que recebe as requisições de um Workload, com um path cuja resposta muda com um argumento de query string. Este guia usa o path `/products` e o argumento `category`. Para criar os dois, consulte [Primeiros passos com Applications](/pt-br/documentacao/plataforma/applications/primeiros-passos/). -- Acesso ao Azion Console. Para entrar, consulte [Como acessar o Azion Console](/pt-br/documentacao/guias/plataforma/conta-e-billing/como-acessar-o-azion-console/). +- Acesso ao Azion Console. Para entrar, consulte [Acesse Azion Console](/pt-br/documentacao/guias/plataforma/conta-e-billing/como-acessar-o-azion-console/). - O `curl`, para requisitar a listagem. @@ -57,7 +57,7 @@ Um cache setting só alcança uma requisição quando uma regra aplica esse cach ### CLI - Uma conta Azion. Para criar uma, consulte [Como criar uma conta na Azion](/pt-br/documentacao/fundamentos/criar-uma-conta/). -- A permissão **Edit Applications** na conta. Ela concede permissão para editar, criar e remover Applications, e também requer a permissão **View Applications**. Consulte [Permissões de equipes](/pt-br/documentacao/fundamentos/teams-permissions/). +- A permissão **Edit Applications** na conta. Ela concede permissão para editar, criar e remover Applications, e também requer a permissão **View Applications**. Para mais informações, consulte [Permissões de equipes](/pt-br/documentacao/fundamentos/teams-permissions/). - Uma Application que recebe as requisições de um Workload, com um path cuja resposta muda com um argumento de query string. Este guia usa o path `/products` e o argumento `category`. Para criar os dois, consulte [Primeiros passos com Applications](/pt-br/documentacao/plataforma/applications/primeiros-passos/). - A [Azion CLI](/pt-br/documentacao/devtools/cli/) instalada e autorizada. - O `curl`, para requisitar a listagem. @@ -69,7 +69,7 @@ Um cache setting só alcança uma requisição quando uma regra aplica esse cach ### API - Uma conta Azion. Para criar uma, consulte [Como criar uma conta na Azion](/pt-br/documentacao/fundamentos/criar-uma-conta/). -- A permissão **Edit Applications** na conta. Ela concede permissão para editar, criar e remover Applications, e também requer a permissão **View Applications**. Consulte [Permissões de equipes](/pt-br/documentacao/fundamentos/teams-permissions/). +- A permissão **Edit Applications** na conta. Ela concede permissão para editar, criar e remover Applications, e também requer a permissão **View Applications**. Para mais informações, consulte [Permissões de equipes](/pt-br/documentacao/fundamentos/teams-permissions/). - Uma Application que recebe as requisições de um Workload, com um path cuja resposta muda com um argumento de query string. Este guia usa o path `/products` e o argumento `category`. Para criar os dois, consulte [Primeiros passos com Applications](/pt-br/documentacao/plataforma/applications/primeiros-passos/). - Um [personal token](/pt-br/documentacao/guias/plataforma/conta-e-billing/personal-tokens/) e o `curl`. @@ -193,7 +193,7 @@ Ativar Application Accelerator pode gerar custos relacionados ao uso. Para mais ## Crie um cache setting que varia por query string -O cache setting guarda o behavior de cache e a variação. O Max Age de `30` segundos que esta etapa define é o ponto do exercício. Sem Application Accelerator, o menor cache TTL que uma Application aceita é 60 segundos. +O cache setting guarda o behavior de cache e a variação. Esta etapa define um Max Age de `30` segundos, que só Application Accelerator permite: sem ele, o menor Max Age que uma Application aceita é 60 segundos. @@ -204,21 +204,36 @@ O cache setting guarda o behavior de cache e a variação. O Max Age de `30` seg Para criar o cache setting pelo Azion Console: + + + Acesse [Azion Console](https://console.azion.com/) > **Applications** > sua Application. + + - Digite um valor em **Name**. Por exemplo: `product-listing`. + Em **Name**, digite um valor. Por exemplo: `product-listing`. - + - Em **Cache**, selecione _Override cache behavior_ e defina **Max Age** como `30`. + Em **Cache**, selecione _Override cache behavior_. - + - Em **Application Accelerator**, abra **Cache vary by Query String** e defina **Behavior** como _Allowlist_. + Em **Max Age**, digite `30`. + + + + + Em **Application Accelerator**, selecione **Cache vary by Query String**. + + + + + Defina **Behavior** como _Allowlist_. @@ -234,7 +249,7 @@ Para criar o cache setting pelo Azion Console: -O cache setting aparece na aba **Cache Settings**. Ele mantém um objeto por 30 segundos e dá a cada valor de `category` o seu próprio objeto em cache. +O cache setting aparece na aba **Cache Settings**. Ele mantém uma cópia por 30 segundos e dá a cada valor de `category` uma cópia separada. @@ -281,7 +296,9 @@ O cache setting aparece na aba **Cache Settings**. Ele mantém um objeto por 30 - --cache-setting-id 123462 --format json`} /> + Substitua `` pelo id que o comando de criação imprimiu: + + --cache-setting-id --format json`} /> Este trecho da saída carrega os campos que o arquivo definiu: @@ -307,7 +324,7 @@ O cache setting aparece na aba **Cache Settings**. Ele mantém um objeto por 30 -O cache setting mantém um objeto por 30 segundos e dá a cada valor de `category` o seu próprio objeto em cache. Guarde o id: a regra da próxima etapa seleciona o cache setting por ele. Para todas as flags que o comando aceita, consulte [`azion create cache-setting`](/pt-br/documentacao/devtools/cli/recursos/cache-setting/#criar). +O cache setting mantém uma cópia por 30 segundos e dá a cada valor de `category` uma cópia separada. Guarde o id: a regra da próxima etapa seleciona o cache setting por ele. Para todas as flags que o comando aceita, consulte [`azion create cache-setting`](/pt-br/documentacao/devtools/cli/recursos/cache-setting/#criar). @@ -371,12 +388,12 @@ Para criar o cache setting com a Azion API, substitua `[TOKEN VALUE]` pelo seu p } ``` - Um `max_age` abaixo de 60 é aceito apenas enquanto Application Accelerator está ativo. + Um `max_age` abaixo de 60 segundos é aceito apenas enquanto Application Accelerator está ativo. -O cache setting mantém um objeto por 30 segundos e dá a cada valor de `category` o seu próprio objeto em cache. Guarde o `id`: a regra da próxima etapa seleciona o cache setting por ele. +O cache setting mantém uma cópia por 30 segundos e dá a cada valor de `category` uma cópia separada. Guarde o `id`: a regra da próxima etapa seleciona o cache setting por ele. @@ -397,11 +414,16 @@ Um cache setting alcança uma requisição apenas quando uma regra aplica esse c Para aplicar o cache setting ao path da listagem pelo Azion Console: + + + Acesse [Azion Console](https://console.azion.com/) > **Applications** > sua Application. + + - Digite um nome para a regra. Por exemplo: `Cache the product listing`. + Em **Name**, digite um nome para a regra. Por exemplo: `Cache the product listing`. @@ -441,12 +463,12 @@ A regra aplica o cache setting a toda requisição cuja URI começa com `/produc ### CLI -Para adicionar a regra com a Azion CLI, envie o corpo a partir de um arquivo, para que o shell mantenha `${uri}` como está escrito. +O corpo vai em um arquivo, para que o shell mantenha `${uri}` como está escrito. Para adicionar a regra com a Azion CLI: - Salve o seguinte como `rule.json`, com o id do seu cache setting em `attributes.value`: + Salve o seguinte como `rule.json` e substitua `` pelo id do seu cache setting: } } ] }`} /> @@ -491,12 +513,12 @@ A regra aplica o cache setting a toda requisição cuja URI começa com `/produc ### API -Para adicionar a regra com a Azion API, substitua `[TOKEN VALUE]` pelo seu personal token e `` pelo ID da sua Application. Envie o corpo a partir de um arquivo, para que o shell mantenha `${uri}` como está escrito. +O corpo vai em um arquivo, para que o shell mantenha `${uri}` como está escrito. Substitua `[TOKEN VALUE]` pelo seu personal token e `` pelo ID da sua Application. Para adicionar a regra com a Azion API: - Salve o seguinte como `rule.json`, com o `id` que a criação do cache setting retornou em `attributes.value`: + Salve o seguinte como `rule.json` e substitua `` pelo `id` que a criação do cache setting retornou: } } ] }`} /> @@ -549,7 +571,7 @@ Uma nova regra pode levar alguns minutos para propagar. Aguarde antes de requisi ## Leia a cache key -A Azion retorna a cache key de um objeto quando a requisição carrega o header de debug da Azion `Pragma: azion-debug-cache`. Ler essa key para dois valores de `category` mostra a variação que o cache setting criou. +A Azion retorna a cache key de um objeto quando a requisição carrega o header de debug da Azion `Pragma: azion-debug-cache`. Ler essa key para dois valores de `category` mostra as cópias separadas que a variação cria. A sua Application recebe as requisições de um Workload, e esse Workload responde no workload domain dele, no formato `xxxxxxxxx.map.azionedge.net`. Para adicionar um domínio a esse Workload, consulte [Adicione um domínio a um workload](/pt-br/documentacao/guias/plataforma/migracao/configurar-dominio/). @@ -576,16 +598,16 @@ O argumento mudou, então a key mudou junto: x-cache-key: httpswww.example.com/products@@?category=hats ``` -Duas keys são dois objetos em cache, que é o que a allowlist pediu. Para o formato completo de uma cache key, consulte [Formato da cache key](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#formato-da-key). +Duas keys são duas cópias separadas, que é o que a allowlist pediu. Para o formato completo de uma cache key, consulte [Formato da cache key](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#formato-da-key). -Sua Application agora mantém a listagem `/products` em cache por 30 segundos e guarda um objeto por valor de `category`. +Sua Application agora mantém a listagem `/products` em cache por 30 segundos e guarda uma cópia separada para cada valor de `category`. --- ## Próximos passos - + diff --git a/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/visao-geral.mdx b/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/visao-geral.mdx index 6b0703c04e..283c9152e1 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/visao-geral.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/application-accelerator/visao-geral.mdx @@ -1,6 +1,6 @@ --- title: Application Accelerator -description: Varie a cache key por query string, cookie, device group ou método com Application Accelerator e armazene uma cópia por variação. +description: Varie a cache key por query string, cookie, device group ou método com Application Accelerator e armazene uma cópia separada para cada valor. meta_tags: 'application accelerator, cache variation, cache key, advanced cache key, query string, cookies, device groups, post and options caching, bypass cache, applications' namespace: documentation_products_application_acceleration permalink: /documentacao/plataforma/applications/application-accelerator/ @@ -10,27 +10,18 @@ import DocButton from '~/components/webkit/DocButton.vue' import DocCardGroup from '@aziontech/webkit/doc-card-group' import DocCard from '@aziontech/webkit/doc-card' -**Application Accelerator** é um recurso da plataforma que libera quatro capacidades para o cache e para as regras de uma [Application](/pt-br/documentacao/plataforma/applications/). Com Application Accelerator ativo, uma Application pode acrescentar mais partes da requisição à cache key, armazenar em cache respostas `POST` e `OPTIONS` e manter uma resposta em cache por menos de 60 segundos. As regras da Application também podem usar mais behaviors do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/), como _Bypass Cache_ e _Forward Cookies_, e mais duas variáveis. - -Um cache guarda cada resposta armazenada sob uma key montada a partir da requisição. Quando essa key contém apenas a URL, todo visitante que requisita a URL recebe a mesma cópia, mesmo quando o conteúdo muda com um cookie, um dispositivo ou um argumento. Acrescentar uma dessas entradas à key dá a cada um dos seus valores uma cópia própria. Uma URL passa então a guardar várias respostas corretas, e cada visitante recebe a que corresponde à sua requisição. - -Em uma Application com Application Accelerator ativo, a key pode receber quatro entradas: um argumento de query string, um cookie, o device group e o método da requisição. Um [device group](/pt-br/documentacao/plataforma/applications/device-groups/) é um nome e uma expressão regular que a Application compara com o header `User-Agent` de cada requisição. - -Application Accelerator vem desativado em uma Application nova, e cada Application o ativa separadamente, no campo `modules.application_accelerator.enabled` da Application na API. Cada [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) da Application guarda por quanto tempo uma resposta fica em cache. Ele também define quais entradas variam a key, no seu próprio objeto `modules.application_accelerator`. Depois, uma [regra](/pt-br/documentacao/plataforma/applications/rules-engine/) com o behavior [Set Cache Policy](/pt-br/documentacao/plataforma/applications/rules-engine/#set-cache-policy) aplica o cache setting às requisições que correspondem à regra. Use Application Accelerator para armazenar em cache cópias separadas de uma página personalizada por um cookie, de uma resposta de API que muda com a sua query string, de um catálogo que difere por dispositivo ou de uma resposta a um `POST`. +**Application Accelerator** é um recurso da plataforma que libera quatro capacidades de cache e regras na infraestrutura distribuída da Azion, para requisições recebidas por [Applications](/pt-br/documentacao/plataforma/applications/). Com ele, uma Application pode variar a cache key por query string, cookie, [device group](/pt-br/documentacao/plataforma/applications/device-groups/) ou método e armazenar em cache respostas `POST` e `OPTIONS`. Os cache settings aceitam um tempo de vida (TTL) mínimo menor, e as regras podem usar behaviors e variáveis do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) reservados a ele. Use Application Accelerator para guardar em cache uma página personalizada por cookie, respostas de API por query string ou catálogos por dispositivo. - + --- ## Caminho da requisição -Uma cache key é a entrada de índice de um objeto em cache. Por padrão, a Azion a monta a partir do scheme, do host e do path da requisição, então cada path é um objeto em cache. A menos que um cache setting varie a key por query string, toda query string de um path aponta para esse único objeto. Cada variação que um cache setting ativa acrescenta uma entrada à key, e cada tipo acrescenta o seu próprio marcador: +Ativar Application Accelerator mantém toda cache key como estava: uma variação só se aplica por meio de uma regra com [Set Cache Policy](/pt-br/documentacao/plataforma/applications/rules-engine/#set-cache-policy). Essa regra aplica o cache setting que guarda a variação às requisições que correspondem a ela. Um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/), o conjunto de valores que diz ao [Cache](/pt-br/documentacao/plataforma/applications/cache/) como e por quanto tempo armazenar e servir uma resposta, guarda as suas variações no seu próprio objeto `modules.application_accelerator`. -- Uma variação por cookie acrescenta o separador `@@`, depois os nomes e os valores dos cookies, cada um seguido de `;`. -- Uma variação por dispositivo acrescenta `@@` e o nome do device group. -- Uma resposta `POST` em cache acrescenta `@@` e o hash MD5 do corpo da requisição. Uma resposta `OPTIONS` em cache acrescenta só o prefixo do método. -- Uma variação por query string sob `allowlist` ou `denylist`, os valores de `behavior` que nomeiam os argumentos a manter ou a deixar de fora, acrescenta `@@`, depois `?` e os argumentos escolhidos. Sob `all`, que varia a key por todo argumento, a query string inteira vem depois do path, antes de `@@`. +Uma cache key é a entrada de índice de um objeto em cache. Por padrão, a Azion a monta a partir do scheme, do host e do path da requisição, então cada path é um objeto em cache. A menos que um cache setting varie a key por query string, toda query string de um path aponta para esse único objeto. Cada variação que um cache setting ativa acrescenta a sua entrada à key com um marcador, como detalha [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#formato-da-key). Uma requisição que usa qualquer método diferente de `GET` ou `HEAD` é uma requisição complexa, e a key dela carrega o método como prefixo. @@ -58,61 +49,13 @@ flowchart TD 1. A requisição chega à Application com o seu scheme, host, path e query string. 2. Uma regra com _Set Cache Policy_ aplica um cache setting à requisição. -3. A key começa com o scheme, o host e o path. Cada variação do objeto `modules.application_accelerator` do cache setting acrescenta então a sua entrada, com o marcador que esta seção lista para ela. -4. Quando [Cache](/pt-br/documentacao/plataforma/applications/cache/) tem uma cópia válida sob essa key, essa cópia se torna a resposta. +3. Cache monta a key a partir da requisição e de cada variação do cache setting. +4. Quando Cache tem uma cópia válida sob essa key, essa cópia se torna a resposta. 5. Caso contrário, o [Connector](/pt-br/documentacao/plataforma/connectors/) encaminha a requisição ao servidor de origem, e Cache guarda a resposta sob essa key. -Uma variação por cookie sobre um cookie `user` produz uma key no formato `httpwww.example.com/@@user=user;`. Um `POST` em cache produz uma no formato `posthttpsdynamic.example.com/path@@md5_of_post_body`. Duas requisições compartilham um objeto em cache quando produzem a mesma key, e recebem objetos separados quando não produzem. Para o formato completo e cada entrada que uma key carrega, consulte [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#formato-da-key). - -Para saber o que ativar Application Accelerator libera, o custo de uma variação e como funcionam os purges, consulte [Variação de cache](/pt-br/documentacao/plataforma/applications/application-accelerator/variacao-de-cache/). Essa página também compara _Bypass Cache_ com um tempo de vida (TTL) de 0. - ---- - -## Estrutura do cache setting - -Um cache setting guarda as entradas que variam a cache key no seu objeto `modules.application_accelerator`, que [Azion Console](https://console.azion.com/) mostra como a seção **Application Accelerator** do setting só enquanto Application Accelerator está ativo na Application. Este cache setting mantém uma listagem de produtos por 30 segundos e dá a cada valor do argumento `category` uma cópia própria. Envie-o como corpo de `POST /v4/workspace/applications//cache_settings`: - -```json -{ - "name": "product-listing", - "browser_cache": { "behavior": "honor" }, - "modules": { - "cache": { - "behavior": "override", - "max_age": 30 - }, - "application_accelerator": { - "cache_vary_by_querystring": { - "behavior": "allowlist", - "fields": ["category"], - "sort_enabled": true - } - } - } -} -``` - -- `modules.application_accelerator` guarda os quatro controles de variação: `cache_vary_by_querystring`, `cache_vary_by_cookies`, `cache_vary_by_devices` e `cache_vary_by_method`. Um controle que o corpo deixa de fora mantém o seu padrão, `ignore`, ou uma lista vazia para os métodos. -- `behavior` aceita `ignore`, `all`, `allowlist` ou `denylist`, e o controle de dispositivos aceita `ignore` ou `allowlist`. Aqui, `allowlist` varia a key apenas pelos argumentos em `fields`, e `sort_enabled` agrupa todas as ordens deles sob uma key. -- `max_age` definido como `30` só é aceito enquanto Application Accelerator está ativo. Sem ele, o piso é de 60 segundos, e [Azion API](https://api.azion.com/) recusa um valor menor com `21021`. -- A Application carrega um objeto `modules.application_accelerator` próprio, e o campo `enabled` dele ativa Application Accelerator. `PATCH /v4/workspace/applications/` o define com `{ "modules": { "application_accelerator": { "enabled": true } } }`. Enquanto esse campo é `false`, a API recusa com `21013` um cache setting que varia o cache: uma variação por query string, por cookie ou por device group cujo `behavior` não é `ignore`, ou um método em `cache_vary_by_method`. - -Se você configurou um header `Vary` ou uma regra de cache key em outro lugar, o modelo se mantém. Você nomeia as entradas que tornam duas requisições diferentes, e cada valor distinto recebe a sua própria cópia. Só os quatro controles de variação definem essas entradas, então um header da requisição como `Accept-Language` não varia a key. - ---- - -## Escopo e limites +Duas requisições compartilham uma cópia quando produzem a mesma key, e recebem cópias separadas quando não produzem. -- **Application**: Application Accelerator vem desativado em uma Application nova e pertence à Application, então uma Application pode tê-lo ativo enquanto outra o tem desativado. Ativá-lo mantém o tráfego como estava: os controles de um cache setting começam em `ignore`, e um cache setting só alcança uma requisição por meio de uma regra com [Set Cache Policy](/pt-br/documentacao/plataforma/applications/rules-engine/#set-cache-policy). [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#recursos-da-plataforma) mostra onde ativá-lo no Azion Console e na API. -- **O que Application Accelerator libera**: variação de cache, o cache de respostas `POST` e `OPTIONS` e um Max Age, o campo `modules.cache.max_age` do cache setting, que pode chegar a 0 segundos. Ele também libera behaviors do Rules Engine e as variáveis `${request_uri}` e `${device_group}`, e uma Application recebe tudo isso ou nada. Os behaviors são _Add Request Cookie_ e _Add Response Cookie_, _Bypass Cache_, _Capture Match Groups_, _Filter Request Cookie_ e _Filter Response Cookie_, _Forward Cookies_ e _Rewrite Request_. Uma Application repassa `POST`, `PUT`, `PATCH`, `DELETE` e `OPTIONS` à origem com ou sem Application Accelerator. Desses métodos, Application Accelerator permite armazenar em cache só as respostas `POST` e `OPTIONS`. -- **Tamanho da variação**: cada valor distinto de uma entrada variada é um objeto em cache separado. Um cookie único para cada visitante dá uma cópia a cada visitante, então o número de objetos cresce com a audiência, e não com o conteúdo. Para saber como uma allowlist e a ordenação, o campo `sort_enabled`, limitam esse número, consulte [Variação de cache](/pt-br/documentacao/plataforma/applications/application-accelerator/variacao-de-cache/#o-custo-de-uma-variacao) e, para as práticas, [Boas práticas de Applications](/pt-br/documentacao/plataforma/applications/boas-praticas/#application-accelerator). -- **Purges**: as variações por cookie e por device group sobrevivem a um purge por URL. Um purge por cache key as alcança, assim como um purge por wildcard que termina a key com `@@*`. As variações por query string são a exceção. Um purge por URL as alcança quando envia os argumentos na ordem em que foram apresentados, ou em ordem alfabética com `sort_enabled` ativo. Para os tipos de purge, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purgue-conteudo-que-varia). -- **Bypass Cache e um TTL de 0**: [Bypass Cache](/pt-br/documentacao/plataforma/applications/rules-engine/#bypass-cache) envia à origem cada requisição que corresponde à sua regra e mantém a resposta fora do cache da Azion. Ele age só sobre o cache da Azion, então a camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) continua a armazenar objetos para uma Application cujos cache settings ativam o Tiered Cache. Um Max Age de 0 segundos mantém a requisição no caminho do cache, e toda requisição ainda chega à origem. Para comparar os dois, consulte [Bypass Cache e um TTL de 0](/pt-br/documentacao/plataforma/applications/application-accelerator/variacao-de-cache/#bypass-cache-e-um-ttl-de-0). -- **Vizinhos**: com Application Accelerator ativo, os controles de variação de um cache setting decidem o que entra em uma key, e [Cache](/pt-br/documentacao/plataforma/applications/cache/) então mantém uma cópia separada para cada valor. Para variar o cache pela string `ims` do [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/), acrescente `ims` à allowlist de query string do cache setting que entrega as imagens. -- **Interfaces**: você ativa Application Accelerator no Azion Console, pela Azion API em `/v4/workspace/applications/` e com `azion update application --application-accelerator` na [Azion CLI](/pt-br/documentacao/devtools/cli/). [`azion.config.js`](/pt-br/documentacao/devtools/cli/azion-config-js/) o define com `applicationAcceleratorEnabled`, e [Azion Lib](/pt-br/documentacao/devtools/azion-lib/application/) com `application_acceleration` em uma atualização. [Azion Terraform Provider](/pt-br/documentacao/devtools/terraform/) gerencia o recurso da Application que carrega o switch. Os controles de variação pertencem ao cache setting, em `/v4/workspace/applications//cache_settings` ou por meio de flags de `azion create cache-setting` como `--cache-by-query-string` e `--cache-by-cookies`. `azion create cache-setting` recebe a variação por device group e o Max Age do cache só em um corpo `--file`. -- **Observabilidade**: com `Pragma: azion-debug-cache` em uma requisição, o header `x-cache-key` da resposta mostra o que cada variação acrescentou à key. Um `POST` informa `-` em `x-cache` até que o campo `cache_vary_by_method` do cache setting carregue `post`. Para verificar o status de cache de uma resposta, consulte [Verifique o status de cache de uma resposta](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/verificar-tempo-de-cache-da-pagina/). -- **Limites**: com Application Accelerator ativo, o Max Age de um cache setting desce até 0 segundos, ou até 3 segundos quando o cache setting também tem Tiered Cache ativo. Ativá-lo pode gerar custos relacionados ao uso. Para cada limite de TTL e a resposta quando ele é ultrapassado, consulte [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#application-accelerator) e, para os valores, [Preços](/pt-br/documentacao/fundamentos/precos/#application-accelerator). A página [Preços da Azion](https://www.azion.com/pt-br/precos/) lista o que cada plano inclui. -- **Termos**: o [glossário de Applications](/pt-br/documentacao/plataforma/applications/glossario/) define as palavras às quais as páginas do Application Accelerator dão um significado específico, como Advanced Cache Key, variação de cache e device group. +Para saber o que ativar Application Accelerator libera, o custo de uma variação e como funcionam os purges, consulte [Variação de cache](/pt-br/documentacao/plataforma/applications/application-accelerator/variacao-de-cache/). Essa página também compara _Bypass Cache_ com um TTL de 0. --- @@ -120,9 +63,11 @@ Se você configurou um header `Vary` ou uma regra de cache key em outro lugar, o - + - - + + + + diff --git a/apps/docs/src/content/docs/pt-br/pages/build/applications/boas-praticas.mdx b/apps/docs/src/content/docs/pt-br/pages/build/applications/boas-praticas.mdx index 1e567fdb67..6b83babba6 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/applications/boas-praticas.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/applications/boas-praticas.mdx @@ -15,7 +15,7 @@ import DocItem from '@aziontech/webkit/doc-item' A maioria dos erros na camada entre os seus usuários e a sua origem fica invisível até que um usuário encontre um deles. Um visitante vê uma versão de uma página que você já substituiu. A origem responde a requisições que uma cópia armazenada poderia ter respondido. Um cookie de sessão chega a um usuário para quem nunca foi emitido, ou uma imagem chega mais pesada ou recortada de forma diferente do que a página pediu. -A causa raramente é um único valor errado. Com mais frequência, uma [cache key](/pt-br/documentacao/plataforma/applications/cache/cache-keys/), a string sob a qual a Azion guarda uma cópia armazenada, varia por algo que a resposta ignora. Ou um único time to live (TTL) cobre conteúdo que muda em ritmos diferentes, ou uma mudança é avaliada antes que alguém leia a resposta. +A causa raramente é um único valor errado. Com mais frequência, uma [cache key](/pt-br/documentacao/plataforma/applications/cache/cache-keys/), a entrada de índice sob a qual Cache armazena uma cópia, varia por algo que a resposta ignora. Ou um único time to live (TTL) cobre conteúdo que muda em ritmos diferentes, ou uma mudança é avaliada antes que alguém leia a resposta. Estas práticas se aplicam a uma [Application](/pt-br/documentacao/plataforma/applications/) e aos seus [device groups](/pt-br/documentacao/plataforma/applications/device-groups/). Elas também cobrem as regras do [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) que agem sobre o seu tráfego e os cache settings que essas regras aplicam. [Como Applications funciona](/pt-br/documentacao/plataforma/applications/como-funciona/) explica os mecanismos por trás delas, e [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/) traz o valor de cada limite. Para as práticas das Functions que uma Application executa, consulte [Boas práticas de Functions](/pt-br/documentacao/plataforma/functions/boas-praticas/). @@ -35,9 +35,9 @@ O custo é a cobertura: um dispositivo da classe cujo header não carrega nenhum ## Envie os headers de upgrade do WebSocket só nas requisições que abrem uma conexão -Por padrão, uma Application com [WebSocket Proxy](/pt-br/documentacao/plataforma/applications/websocket/) ativado faz proxy de toda requisição com `Upgrade: websocket` e `Connection: upgrade` para a origem como uma conexão WebSocket, qualquer que seja o path. Controle esses headers na aplicação que você constrói e envie-os só onde o protocolo WebSocket deve ser usado. +Por padrão, uma Application com [WebSocket Proxy](/pt-br/documentacao/plataforma/applications/websocket/) ativado trata como conexão WebSocket toda requisição com `Upgrade: websocket` e `Connection: upgrade`. Ela faz proxy dessa conexão para a origem, qualquer que seja o path. Controle esses headers na aplicação que você constrói e envie-os só onde o protocolo WebSocket deve ser usado. -A decisão fica então no código do seu cliente. O mesmo cliente também reabre uma conexão que se fecha. A Azion recicla as conexões keepalive aproximadamente a cada 15 minutos, o que pode fechar uma conexão WebSocket ativa. +A decisão fica então no código do seu cliente. O mesmo cliente também reabre uma conexão que se fecha. A Azion recicla as conexões keepalive aproximadamente a cada 15 minutos, o que pode fechar uma conexão WebSocket ativa, como lista [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/). Uma conexão que se abre retorna `101 Switching Protocols`, e qualquer outro status, mesmo um `2xx` ou um `3xx`, significa que o upgrade não se completou. Para os headers e os status, consulte [WebSocket Proxy](/pt-br/documentacao/plataforma/applications/websocket/#headers-de-upgrade). @@ -45,13 +45,13 @@ Uma conexão que se abre retorna `101 Switching Protocols`, e qualquer outro sta ## Cache -Um cache setting pertence a uma Application e guarda por quanto tempo a Azion e o navegador mantêm uma resposta, e o que torna duas requisições diferentes. Mantida por tempo demais, uma cópia mostra a um visitante um conteúdo que a origem já substituiu. Mantida por pouco tempo, ela envia à origem requisições que uma cópia armazenada poderia ter respondido. +Um cache setting é um conjunto de valores que dizem ao Cache como armazenar e entregar uma resposta. Ele pertence a uma Application e guarda por quanto tempo a Azion e o navegador mantêm uma resposta, e o que torna duas requisições diferentes. Mantida por tempo demais, uma cópia mostra a um visitante um conteúdo que a origem já substituiu. Mantida por pouco tempo, ela envia à origem requisições que uma cópia armazenada poderia ter respondido. -Estas práticas se aplicam aos [cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) de uma Application e às regras que aplicam esses cache settings por meio do behavior _Set Cache Policy_. Elas tratam, em ordem, do TTL, do nome de um objeto, do purge das suas variações, de Tiered Cache, de stale cache e do status de cache de uma resposta. A primeira prática mostra um cache setting completo, na forma que a API aceita, e as práticas seguintes nomeiam só o campo que mudam. A última prática mostra como confirmar cada mudança na resposta. +Estas práticas se aplicam aos [cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) de uma Application e às regras que aplicam esses cache settings por meio do behavior _Set Cache Policy_. Elas tratam, em ordem, do TTL, do nome de um objeto, do purge das suas cópias, de Tiered Cache, de stale cache e do status de cache de uma resposta. A primeira prática mostra um cache setting completo, na forma que a API aceita, e as práticas seguintes nomeiam só o campo que mudam. A última prática mostra como confirmar cada mudança na resposta. ### Ajuste cada TTL à frequência com que o seu conteúdo muda -Sob o comportamento `override`, o Max Age de um cache setting define o TTL de uma cópia, no seu campo `modules.cache.max_age`. Um TTL mais longo responde a mais requisições, mas fica mais atrasado em relação à origem. Assets podem mudar só quando um deploy os substitui, enquanto uma página muda ao longo do dia, então um único TTL não serve para parte do conteúdo. +Sob _Override cache behavior_ (`override`), o Max Age de um cache setting define o TTL de uma cópia, no seu campo `modules.cache.max_age`. Um TTL mais longo responde a mais requisições, mas fica mais atrasado em relação à origem. Assets podem mudar só quando um deploy os substitui, enquanto uma página muda ao longo do dia, então um único TTL não serve para parte do conteúdo. Dê a cada grupo de paths que muda em um mesmo ritmo o seu próprio cache setting e a sua própria regra. Este setting mantém os assets por 86.400 segundos no navegador e por 300 segundos na Azion: @@ -69,22 +69,22 @@ Páginas editadas durante o dia recebem um segundo setting e uma segunda regra, ### Mude o nome de um objeto quando o conteúdo dele mudar -Um objeto que mantém o nome exige um purge de cada camada de cache e de cada variação sempre que o seu conteúdo muda. Em vez disso, coloque uma versão no nome do arquivo. O cache trata cada versão como um objeto separado, e a primeira requisição para ela busca os bytes atuais na origem. Qualquer esquema serve, como um contador, um timestamp ou um hash do conteúdo, desde que conteúdo diferente sempre receba um nome diferente: `https://static.example.com/assets/image_1.jpg` passa a ser `https://static.example.com/assets/image_2.jpg`. +Um objeto que mantém o nome exige um purge de cada camada de cache e de cada cópia sempre que o seu conteúdo muda. Em vez disso, coloque uma versão no nome do arquivo. O cache trata cada versão como um objeto separado, e a primeira requisição para ela busca os bytes atuais na origem. Qualquer esquema serve, como um contador, um timestamp ou um hash do conteúdo, desde que conteúdo diferente sempre receba um nome diferente: `https://static.example.com/assets/image_1.jpg` passa a ser `https://static.example.com/assets/image_2.jpg`. -Uma atualização chega aos usuários sem purge, e um navegador que ainda guarda o nome anterior mantém um objeto válido. As duas versões ficam disponíveis, então reverter significa apontar as suas páginas para o nome anterior. O custo é que toda referência ao objeto muda junto com ele, o que uma etapa de build pode automatizar e uma edição manual não pode. +Uma atualização chega aos usuários sem purge, e um navegador que ainda guarda o nome anterior mantém um objeto válido. As duas versões ficam disponíveis, então reverter significa apontar as suas páginas para o nome anterior. O custo é que toda referência ao objeto muda junto com ele, o que uma etapa de build pode automatizar e uma edição manual não pode. A primeira resposta para o nome novo informa `MISS` em `x-cache`, como mostra [Leia o status de cache depois de cada mudança de cache](/pt-br/documentacao/plataforma/applications/boas-praticas/#leia-o-status-de-cache-depois-de-cada-mudanca-de-cache). ### Purgue um objeto que varia por cache key ou wildcard -[Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/) encontra uma cópia pela sua cache key, e um objeto que varia tem uma key por variação. Um purge por URL converte a URL em uma key. Uma cópia que varia por cookie, device group ou formato de imagem sobrevive a ele, enquanto o purge informa sucesso. +[Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/) encontra uma cópia pela sua cache key, e um objeto que varia tem uma key por cópia. Um purge por URL converte a URL em uma key. Uma cópia que varia por cookie, device group ou formato de imagem sobrevive a ele, enquanto o purge informa sucesso. -Nomeie essas keys em um purge por cache key, até 50 por requisição, ou alcance-as com um wildcard. Estes comandos da [Azion CLI](/pt-br/documentacao/devtools/cli/) enviam os dois, com o wildcard terminado em `@@*` para as variações por cookie: +Nomeie essas keys em um purge por cache key, até 50 por requisição, como lista [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#real-time-purge), ou alcance-as com um wildcard. Estes comandos da [Azion CLI](/pt-br/documentacao/devtools/cli/) enviam os dois, com o wildcard terminado em `@@*` para as variações por cookie: ```bash azion purge --cachekey "httpwww.example.com/@@user=user;" azion purge --wildcard "www.example.com/@@*" ``` -Cada comando imprime `Purge carried out successfully`. Uma variação com muitos valores custa mais para purgar e para armazenar, então escolha o seu purge quando escolher a variação. Para o purge que alcança cada variação, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purgue-conteudo-que-varia). Para os passos, consulte [Purgue conteúdo em cache](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/purgar-conteudo-em-cache/). +Cada comando imprime `Purge carried out successfully`. Uma variação com muitos valores custa mais para purgar e para armazenar, então escolha o seu purge quando escolher a variação. Para o purge que alcança cada cópia, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purgue-conteudo-que-varia). Para os passos, consulte [Purgue conteúdo em cache](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/purgar-conteudo-em-cache/). ### Reserve Tiered Cache para objetos de vida longa com corpo estável @@ -96,7 +96,9 @@ A camada fica fora do alcance de uma regra com _Bypass Cache_, como explica [Des ### Ative stale cache onde uma página antiga é melhor que um erro -Com stale cache ativo em um cache setting, a Azion serve uma cópia além do seu TTL quando a revalidação com a origem falha. Ela faz isso pelo valor de `stale-while-revalidate` da origem sob o comportamento `honor`, e por 300 segundos nos demais casos. O visitante recebe a última versão boa em vez de uma página de erro. Defina `modules.cache.stale_cache.enabled` como `true` para um artigo, uma listagem ou uma página de produto. Mantenha-o desativado para um preço ou um dado de disponibilidade em que um visitante baseia uma decisão. +Com stale cache ativo em um cache setting, a Azion serve uma cópia além do seu TTL quando a revalidação com a origem falha. Ela faz isso pelo valor de `stale-while-revalidate` da origem sob _Honor cache policies_ (`honor`), e por 300 segundos nos demais casos. O visitante recebe a última versão boa em vez de uma página de erro. + +Defina `modules.cache.stale_cache.enabled` como `true` para um artigo, uma listagem ou uma página de produto. Mantenha-o desativado para um preço ou um dado de disponibilidade em que um visitante baseia uma decisão. Uma resposta servida assim informa `STALE` em `x-cache`. Para a duração da janela, o que faz uma revalidação falhar e quando um purge serve melhor que a expiração, consulte [Expiração e atualização](/pt-br/documentacao/plataforma/applications/cache/expiracao-e-atualizacao/#stale-cache). @@ -116,9 +118,9 @@ Uma resposta descreve uma cópia em um servidor, então repita a requisição an ## Application Accelerator -Cada atributo pelo qual uma cache key varia multiplica as cópias que a Azion mantém de uma URL, uma cópia por valor. Quando o atributo não altera a resposta, essas cópias carregam bytes idênticos, dividem o tráfego entre si e acrescentam keys que um purge precisa alcançar. +Application Accelerator permite que um cache setting varie a cache key. Cada atributo pelo qual a key varia multiplica as cópias que a Azion mantém de uma URL, uma cópia por valor. Quando o atributo não altera a resposta, essas cópias carregam bytes idênticos, dividem o tráfego entre si e acrescentam keys que um purge precisa alcançar. -[Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/) libera behaviors do Rules Engine como _Bypass Cache_ e _Forward Cookies_ e permite que um cache setting altere os campos do seu objeto `modules.application_accelerator`. Enquanto ele está desativado na Application, a API recusa com `21013` uma variação nesses campos, um `behavior` diferente de `ignore` ou um método em `cache_vary_by_method`. +[Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/) libera behaviors do Rules Engine como _Bypass Cache_ e _Forward Cookies_ e permite que um cache setting altere os campos do seu objeto `modules.application_accelerator`. Enquanto ele está desativado na Application, a API recusa com `21013` qualquer variação nesses campos: um `behavior` diferente de `ignore` ou um método em `cache_vary_by_method`. As quatro primeiras práticas moldam a key: a query string, a ordem dela, os cookies e os cookies de sessão sob _Forward Cookies_. `x-cache-key` mostra o que cada uma delas acrescenta, como explica [Leia o status de cache depois de cada mudança de cache](/pt-br/documentacao/plataforma/applications/boas-praticas/#leia-o-status-de-cache-depois-de-cada-mudanca-de-cache). A última trata de _Bypass Cache_ e da camada do Tiered Cache que ele deixa intacta. @@ -145,25 +147,25 @@ Uma lista vazia é recusada com `21018`. Deixe de fora um argumento que muda a r ### Ordene a query string antes que ela entre na key -Sem ordenação, os argumentos listados entram na cache key na ordem em que o cliente os escreveu. `?category=shoes&page=2` e `?page=2&category=shoes` passam então a ser duas cópias da mesma resposta. Com `sort_enabled` definido como `true` no mesmo objeto `cache_vary_by_querystring`, os argumentos entram na key em ordem alfabética, e as duas requisições chegam a uma única cópia. +Sem ordenação, os argumentos listados entram na cache key na ordem do cliente. `?category=shoes&page=2` e `?page=2&category=shoes` passam então a ser duas cópias da mesma resposta. Com `sort_enabled` definido como `true` no mesmo objeto `cache_vary_by_querystring`, os argumentos entram na key em ordem alfabética, e as duas requisições chegam a uma única cópia. -O custo aparece na hora do purge: um purge por URL alcança a cópia só quando nomeia os argumentos em ordem alfabética. Quando a Azion CLI cria um cache setting, só `--file` e um corpo JSON definem `sort_enabled`. Em uma atualização, `--enable-caching-string-sort` o define. Para ver qual purge alcança cada variação, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purgue-conteudo-que-varia). +O custo aparece na hora do purge: um purge por URL alcança a cópia só quando nomeia os argumentos em ordem alfabética. Na Azion CLI, só `--file` define `sort_enabled` na criação, e `--enable-caching-string-sort` o define em uma atualização, como lista [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#application-accelerator). Para ver qual purge alcança cada cópia, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purgue-conteudo-que-varia). ### Liste só os cookies que segmentam conteúdo -Os navegadores enviam todos os cookies que guardam para um domínio, e poucos deles mudam o que a origem retorna. Sob `all`, um identificador de analytics ou uma flag de consentimento entra na key, e as cópias se multiplicam com os valores dos cookies, e não com o conteúdo. Sob `allowlist`, só os cookies que você nomeia variam a key, e é assim que uma Application segmenta conteúdo por perfil de usuário ou por outro agrupamento. +Os navegadores enviam todos os cookies que guardam para um domínio, e poucos deles mudam o que a origem retorna. Sob `all`, um identificador de analytics ou uma flag de consentimento entra na key, e as cópias se multiplicam com os valores dos cookies, e não com o conteúdo, até uma cópia por visitante para um cookie único por visitante. Sob `allowlist`, só os cookies que você nomeia variam a key, e é assim que uma Application segmenta conteúdo por perfil de usuário ou por outro agrupamento. -Use a allowlist quando cookies gerenciam sessões de usuário: `behavior` definido como `allowlist` e `session_id` em `cookie_names`, sob `modules.application_accelerator.cache_vary_by_cookies`. O custo são as cópias: um cookie único por visitante significa uma cópia por visitante. Para os passos, consulte [Configure a Advanced Cache Key para uma aplicação](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/advanced-cache-key/). +Nomeie em `cookie_names` só os cookies que mudam a resposta, com `behavior` definido como `allowlist`. Para os passos, consulte [Configure a Advanced Cache Key para uma aplicação](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/advanced-cache-key/). ### Coloque os cookies de sessão na allowlist onde Forward Cookies roda -O behavior [Forward Cookies](/pt-br/documentacao/plataforma/applications/rules-engine/#forward-cookies) repassa aos usuários o header `Set-Cookie` da origem, incluindo os cache hits. Uma resposta em cache pode então entregar a um usuário o `Set-Cookie` da sessão de outro usuário. Nomeie o cookie de sessão em uma allowlist, para que cada sessão receba a sua própria key: `behavior` definido como `allowlist`, com `session_id` em `cookie_names`. Uma `denylist` que nomeia `session_id` deixa o cookie fora da key, e as sessões compartilham um único objeto. +O behavior [Forward Cookies](/pt-br/documentacao/plataforma/applications/rules-engine/#forward-cookies) repassa aos usuários o header `Set-Cookie` da origem, incluindo os cache hits. Uma resposta em cache pode então entregar a um usuário o `Set-Cookie` da sessão de outro usuário. Nomeie o cookie de sessão em uma allowlist, para que cada sessão receba a sua própria key: sob `modules.application_accelerator.cache_vary_by_cookies`, `behavior` definido como `allowlist`, com `session_id` em `cookie_names`. Uma `denylist` que nomeia `session_id` deixa o cookie fora da key, e as sessões compartilham um único objeto. Coloque a allowlist no cache setting que a regra com Forward Cookies aplica por meio de _Set Cache Policy_. Para os passos, consulte [Configure políticas de cache para uma aplicação](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/cache-settings/#encaminhe-cookies-da-origem-ao-usuario). ### Descarte Tiered Cache antes de contar com Bypass Cache -O behavior [Bypass Cache](/pt-br/documentacao/plataforma/applications/rules-engine/#bypass-cache) impede que o cache da Azion armazene a resposta da origem, mas a camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/#bypass-cache) fica fora do alcance da regra. Enquanto a regra está ativa, uma camada que os cache settings ativam continua armazenando objetos em cache pelo Max Age do cache setting, cujo piso é de 3 segundos com Tiered Cache ativo. A camada aparece só nos cache settings, e não na regra, então uma regra que parece certa ainda pode deixar conteúdo em cache. +O behavior [Bypass Cache](/pt-br/documentacao/plataforma/applications/rules-engine/#bypass-cache) envia à origem as requisições às quais a sua regra corresponde e mantém a resposta fora do cache da Azion. A camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/#bypass-cache) fica fora do alcance da regra. Enquanto a regra está ativa, uma camada que os cache settings ativam continua armazenando objetos em cache pelo Max Age do cache setting, cujo piso é de 3 segundos com Tiered Cache ativo. A camada aparece só nos cache settings, e não na regra, então uma regra que parece certa ainda pode deixar conteúdo em cache. Quando o requisito é conteúdo atualizado, procure `modules.cache.tiered_cache.enabled` definido como `true` nos cache settings que cobrem os paths da regra. Se nenhuma camada puder manter uma cópia, decida sobre Tiered Cache junto com a regra. Para o sintoma que uma camada esquecida produz e a sua correção, consulte [O conteúdo continua sendo entregue do cache depois de uma regra com Bypass Cache](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#o-conteudo-continua-sendo-entregue-do-cache-depois-de-uma-regra-com-bypass-cache). @@ -171,9 +173,15 @@ Quando o requisito é conteúdo atualizado, procure `modules.cache.tiered_cache. ## Image Processor -Uma imagem transformada pode prejudicar uma página de três formas. O arquivo pesa mais do que a página precisa, ou o recorte remove algo que ninguém pretendia remover. Ou a imagem chega em um formato que o cliente não consegue exibir. Em torno da transformação, o cache setting decide como as imagens derivadas são armazenadas e com que frequência a mesma requisição chega de novo a Image Processor. +Image Processor transforma uma imagem sob demanda, e uma imagem transformada pode prejudicar uma página de três formas: + +- O arquivo pesa mais do que a página precisa. +- O recorte remove algo que ninguém pretendia remover. +- A imagem chega em um formato que o cliente não consegue exibir. + +Em torno da transformação, o cache setting decide como as imagens derivadas são armazenadas e com que frequência a mesma requisição chega de novo a Image Processor. -Estas práticas se aplicam a [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/): a query string `ims`, a regra cujo behavior _Optimize Images_ age sobre essa query string e o cache setting dessa regra. As três primeiras práticas tratam da requisição: a qualidade, o redimensionamento e o header `Accept`. As duas últimas tratam do cache setting: a allowlist e o TTL dele. `x-cache` e `x-cache-key` mostram o resultado dessas duas, como explica [Leia o status de cache depois de cada mudança de cache](/pt-br/documentacao/plataforma/applications/boas-praticas/#leia-o-status-de-cache-depois-de-cada-mudanca-de-cache). +Estas práticas se aplicam a [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/): o parâmetro `ims`, a regra cujo behavior _Optimize Images_ age sobre esse parâmetro e o cache setting dessa regra. As três primeiras práticas tratam da requisição: a qualidade, o redimensionamento e o header `Accept`. As duas últimas tratam do cache setting: a allowlist e o TTL dele. `x-cache` e `x-cache-key` mostram o resultado dessas duas, como explica [Leia o status de cache depois de cada mudança de cache](/pt-br/documentacao/plataforma/applications/boas-praticas/#leia-o-status-de-cache-depois-de-cada-mudanca-de-cache). ### Solicite qualidade 85, a menos que uma imagem precise de outro valor @@ -189,7 +197,7 @@ Em uma fotografia em paisagem, `?ims=400x400` recorta a imagem para preencher o ### Adicione o header Accept só onde todo cliente exibe WEBP -Um behavior [Add Request Header](/pt-br/documentacao/plataforma/applications/rules-engine/#add-request-header) com `Accept: image/webp` faz a conversão automática entregar WEBP a toda requisição a que a regra corresponde, inclusive a uma cujo cliente pediu PNG. Um filtro `filters:format()` não precisa dele: a resposta traz o formato nomeado, qualquer que seja o header `Accept` da requisição. Adicione o header só quando todo cliente desses paths exibir WEBP. +Um behavior [Add Request Header](/pt-br/documentacao/plataforma/applications/rules-engine/#add-request-header) com `Accept: image/webp` faz a conversão automática entregar WEBP a toda requisição a que a regra corresponde. Isso inclui uma requisição cujo cliente pediu PNG. Um filtro `filters:format()` não precisa dele: a resposta traz o formato nomeado, qualquer que seja o header `Accept` da requisição. Adicione o header só quando todo cliente desses paths exibir WEBP. A API recebe o behavior como `{ "type": "add_request_header", "attributes": { "value": "Accept: image/webp" } }` na Request Phase da regra e rejeita o tipo `add_header` com `10039`. Para o filtro de conversão, consulte [Parâmetros de URL do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/parametros-de-url/#conversao-de-formato). Para os critérios que restringem uma regra a requisições de imagem, consulte [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/#behaviors-do-rules-engine). @@ -197,13 +205,13 @@ A API recebe o behavior como `{ "type": "add_request_header", "attributes": { "v `ims` carrega a transformação, então é um argumento de que a resposta depende. [Monte a cache key só com os argumentos de que a resposta depende](/pt-br/documentacao/plataforma/applications/boas-praticas/#monte-a-cache-key-so-com-os-argumentos-de-que-a-resposta-depende) se aplica a ele. O cache setting que a regra de imagens aplica define `fields` como `["ims"]` sob uma `allowlist`. -A diferença é um segundo recurso da plataforma: `cache_vary_by_querystring` pertence a `modules.application_accelerator`, então essa allowlist exige Application Accelerator, embora transformar uma imagem não exija. Para os controles do Azion Console que definem o campo, consulte [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/#variacao-de-cache). +Essa allowlist exige um segundo recurso da plataforma: `cache_vary_by_querystring` pertence a `modules.application_accelerator`, então a allowlist exige Application Accelerator, embora transformar uma imagem não exija. Para os controles do Azion Console que definem o campo, consulte [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/#variacao-de-cache). ### Mantenha imagens derivadas em cache pelo tempo que as imagens de origem permitirem -Image Processor soma uma imagem ao medidor mensal Images para cada requisição que processa, seja para redimensionar, recortar, converter ou filtrar a imagem. Uma requisição que o cache responde não executa transformação e não acrescenta nada. Um Max Age curto envia a mesma requisição a Image Processor de novo, em um intervalo sem relação com mudanças na imagem de origem. +Image Processor conta uma imagem processada para cada requisição que transforma, seja para redimensionar, recortar, converter ou filtrar a imagem. Uma requisição que o cache responde não executa transformação e não acrescenta nada a essa contagem. Um Max Age curto envia a mesma requisição a Image Processor de novo, em um intervalo sem relação com mudanças na imagem de origem. -Dê ao cache setting das imagens derivadas o maior `modules.cache.max_age` que o seu conteúdo de origem tolera, até 31.536.000 segundos. O custo é a atualização do conteúdo. Uma imagem de origem substituída deixa as suas versões derivadas, uma key por processamento e por formato, em cache até expirarem ou até que um purge as remova. Para as imagens que cada plano inclui, consulte [Preços da Azion](https://www.azion.com/pt-br/precos/). +Dê ao cache setting das imagens derivadas o maior `modules.cache.max_age` que o seu conteúdo de origem tolera, até os 31.536.000 segundos que [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#cache) permite. O custo é a atualização do conteúdo. Uma imagem de origem substituída deixa as suas versões derivadas, uma key por processamento e por formato, em cache até expirarem ou até que um purge as remova. Para como as imagens processadas são cobradas e as imagens que cada plano inclui, consulte [Preços da Azion](https://www.azion.com/pt-br/precos/). --- diff --git a/apps/docs/src/content/docs/pt-br/pages/build/applications/como-funciona.mdx b/apps/docs/src/content/docs/pt-br/pages/build/applications/como-funciona.mdx index 2678920aa5..7a987dd148 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/applications/como-funciona.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/applications/como-funciona.mdx @@ -9,13 +9,15 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Entre um cliente e o seu conteúdo, uma camada pode ler cada requisição primeiro, seja ela para uma página, um arquivo ou uma rota de API. A camada então decide o que acontece com a requisição. Ela pode executar um código que constrói a resposta sem nenhum servidor atrás da camada, ficar na frente do servidor que guarda o seu conteúdo ou fazer as duas coisas. Na frente desse servidor, ela pode responder com uma cópia de uma resposta que o servidor enviou antes, adicionar ou remover um header ou escolher o servidor que recebe a requisição. Quando uma resposta volta desse servidor, a mesma camada pode alterá-la antes que o cliente a receba. +Entre um cliente e o seu conteúdo, uma camada pode ler cada requisição primeiro, seja ela para uma página, um arquivo ou uma rota de API. A camada então decide o que acontece com a requisição. Ela pode executar um código que constrói a resposta sem nenhum servidor atrás da camada, ficar na frente do servidor que guarda o seu conteúdo ou fazer as duas coisas. -Na Azion, essa camada é uma Application. [Applications](/pt-br/documentacao/plataforma/applications/) é um recurso da plataforma que processa as requisições recebidas pelos seus [Workloads](/pt-br/documentacao/plataforma/workloads/), na infraestrutura distribuída da Azion, a partir do data center mais próximo ao seu usuário. Cada requisição chega a uma Application por meio de um Workload, que recebe a requisição em um dos seus domínios. O deployment do Workload define a Application que processa a requisição. +Na frente desse servidor, ela pode responder com uma cópia de uma resposta que o servidor enviou antes, adicionar ou remover um header ou escolher o servidor que recebe a requisição. Quando uma resposta volta desse servidor, a mesma camada pode alterá-la antes que o cliente a receba. -A Application age sobre a requisição por meio das suas regras, que você escreve em [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/). Cada regra pertence a uma de duas fases: as regras da Request Phase agem sobre a requisição, e as regras da Response Phase agem sobre a resposta que o usuário recebe. Para enviar a requisição à origem, uma regra da Request Phase usa o behavior _Set Connector_, que define o [Connector](/pt-br/documentacao/plataforma/connectors/) que encaminha a requisição até lá. Uma regra também pode executar o seu código sobre a requisição: o behavior _Run Function_ invoca uma [Function Instance](/pt-br/documentacao/plataforma/applications/functions-instances/) de uma das suas [Functions](/pt-br/documentacao/plataforma/functions/). +Na Azion, essa camada é uma Application. [Applications](/pt-br/documentacao/plataforma/applications/) é um recurso da plataforma que processa as requisições recebidas pelos seus [Workloads](/pt-br/documentacao/plataforma/workloads/), a partir do data center mais próximo ao seu usuário. Cada requisição chega a uma Application por meio de um Workload, que recebe a requisição em um dos seus domínios. -Três recursos da plataforma aninhados em Applications agem no caminho do Workload até a origem, cada um com o seu próprio switch na Application. [Cache](/pt-br/documentacao/plataforma/applications/cache/) responde com uma cópia armazenada de uma resposta anterior. [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) libera quatro capacidades para o cache e para as regras de uma Application. Entre elas, a variação de cache acrescenta mais partes da requisição, como um cookie ou um argumento de query string, à cache key, o índice sob o qual Cache arquiva cada cópia. [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) constrói uma imagem redimensionada ou convertida a partir de uma imagem na origem. +A Application age sobre a requisição por meio das suas regras, que você escreve em [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) e que são executadas em duas fases, primeiro sobre a requisição e depois sobre a resposta. Uma regra pode definir o [Connector](/pt-br/documentacao/plataforma/connectors/) que encaminha a requisição à sua origem ou invocar uma [Function Instance](/pt-br/documentacao/plataforma/applications/functions-instances/) de uma das suas [Functions](/pt-br/documentacao/plataforma/functions/). + +Três recursos da plataforma aninhados em Applications agem no caminho do Workload até a origem, cada um com o seu próprio switch na Application. [Cache](/pt-br/documentacao/plataforma/applications/cache/) responde com uma cópia armazenada de uma resposta anterior, e [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) libera quatro capacidades para o cache e para as regras de uma Application. [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) constrói uma imagem redimensionada ou convertida a partir de uma imagem na origem. Esta página explica os mecanismos, e outras duas páginas guardam os campos: Rules Engine para Applications lista cada variável, operador e behavior, e [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/) lista cada limite. As seções acompanham uma requisição pelo seu caminho e depois cobrem as duas fases, como as regras são executadas, o que uma Application nova tem e a propagação. Depois delas, uma seção para cada um cobre Cache, Application Accelerator e Image Processor. [WebSocket Proxy](/pt-br/documentacao/plataforma/applications/websocket/) cobre, em uma página própria, as conexões WebSocket que uma Application repassa à origem, e [Como Functions funciona](/pt-br/documentacao/plataforma/functions/como-funciona/) cobre como uma Function é executada. @@ -23,9 +25,11 @@ Esta página explica os mecanismos, e outras duas páginas guardam os campos: Ru ## O caminho que uma requisição percorre -Criar uma Application não a coloca no caminho de nenhuma requisição: uma requisição só chega à Application depois que o deployment de um Workload define essa Application. A relação fica guardada no deployment, não na Application, e no Azion Console você define essa relação no campo **Application** das **Deployment Settings** do Workload. O deployment também pode definir um [Firewall](/pt-br/documentacao/plataforma/firewall/), e a requisição então passa pelo Firewall antes que a Application a receba. Os domínios, os protocolos e os certificados também ficam no Workload, então você configura a entrega no Workload, não na Application. +Criar uma Application não a põe no caminho de requisições: ela só as recebe depois que o deployment de um Workload define essa Application. A relação fica guardada no deployment, não na Application, e [Entregue a Application por um Workload](/pt-br/documentacao/plataforma/applications/primeiros-passos/#entregue-a-application-por-um-workload) mostra como defini-la. O deployment também pode definir um [Firewall](/pt-br/documentacao/plataforma/firewall/), e a requisição então passa pelo Firewall antes que a Application a receba. Os domínios, os protocolos e os certificados também ficam no Workload, então você configura a entrega no Workload, não na Application. + +A Application também não guarda uma origem: uma requisição só chega a uma origem quando uma regra da Request Phase a envia para lá com o behavior _Set Connector_. Esse behavior define um Connector, e o Connector guarda o endereço da origem. Uma Application criada só com `name` e `active` volta sem nenhum campo que aponte para um servidor, como mostra [O que uma Application nova tem](/pt-br/documentacao/plataforma/applications/como-funciona/#o-que-uma-application-nova-tem). -A Application também não guarda uma origem: uma requisição só chega a uma origem quando uma regra da Request Phase a envia para lá com o behavior _Set Connector_. Esse behavior define um Connector, e o Connector guarda o endereço da origem. A API mostra isso: uma Application criada só com `name` e `active` volta com `modules`, `active` e `debug`, e sem nenhum campo que aponte para um servidor. Os Connectors substituem as origens que as versões anteriores de Applications configuravam na Application. No lugar de uma origem, uma Function pode responder a uma requisição: uma regra executa a Function com _Run Function_, e a Function constrói a resposta sem nenhum Connector. +Os Connectors substituem as origens que as versões anteriores de Applications configuravam na Application. No lugar de uma origem, uma Function pode responder a uma requisição: uma regra executa a Function com _Run Function_, e a Function constrói a resposta sem nenhum Connector. O diagrama acompanha uma requisição no caminho até uma origem, do cliente até a resposta que ele recebe. As setas sólidas levam a requisição, e as setas pontilhadas levam a resposta. Cada rótulo começa com o número do seu passo abaixo. @@ -66,7 +70,9 @@ Como uma regra escolhe a origem de cada requisição, uma Application pode encam ## Fases de requisição e de resposta -Cada regra de uma Application pertence a uma fase, e as duas fases são executadas em uma ordem fixa: a Request Phase antes que exista uma resposta, depois a Response Phase sobre a resposta que a Application entrega. Você define a fase de uma regra quando a cria e não pode mudá-la depois. Na API, o endpoint que recebe a regra define a fase dela: `request_rules` ou `response_rules`. Para executar a mesma lógica na outra fase, adicione uma segunda regra nessa fase. +Cada regra pertence a uma de duas fases, e as fases são executadas em uma ordem fixa: a Request Phase, depois a Response Phase. A Request Phase é executada antes que exista uma resposta, e a Response Phase é executada sobre a resposta que a Application entrega. + +Você define a fase de uma regra quando a cria e não pode mudá-la depois. Na API, o endpoint que recebe a regra define a fase dela: `request_rules` ou `response_rules`. Para executar a mesma lógica na outra fase, adicione uma segunda regra nessa fase. O diagrama acompanha uma requisição no caminho até uma origem. As setas sólidas levam a requisição, e as setas pontilhadas levam a resposta. Cada rótulo começa com o número do seu passo abaixo. @@ -96,7 +102,9 @@ flowchart TD Como a Request Phase é executada primeiro, o cache é decidido antes que a resposta exista. Uma regra não pode aplicar um cache setting com base no status code que a origem retorna, porque `${status}` só pode ser lido na Response Phase e _Set Cache Policy_ só é executado na Request Phase. -Alguns behaviors funcionam nas duas fases, e a fase limita o que eles fazem. Em uma regra da Response Phase, _Redirect To_ só é executado quando a origem retorna `404`. Então, um redirecionamento nessa fase pode enviar o usuário para outra página quando a origem não tem nada no path e deixar intactas as requisições para paths que existem. _Run Function_ também funciona nas duas fases, mas a Response Phase só aceita Functions escritas em Lua. O formulário da Function Instance no Azion Console informa esse limite: `Only Lua functions can be used in the Response phase.` [Fases](/pt-br/documentacao/plataforma/applications/rules-engine/#fases) lista as variáveis e os behaviors que cada fase aceita. +Alguns behaviors funcionam nas duas fases, e a fase limita o que eles fazem. Em uma regra da Response Phase, _Redirect To_ só é executado quando a origem retorna `404`. Então, um redirecionamento nessa fase pode enviar o usuário para outra página quando a origem não tem nada no path e deixar intactas as requisições para paths que existem. + +_Run Function_ também funciona nas duas fases, mas a Response Phase só aceita Functions escritas em Lua. O formulário da Function Instance no Azion Console informa esse limite: `Only Lua functions can be used in the Response phase.` [Fases](/pt-br/documentacao/plataforma/applications/rules-engine/#fases) lista as variáveis e os behaviors que cada fase aceita. --- @@ -138,7 +146,7 @@ Alguns behaviors não podem ficar juntos na mesma regra, e a API e Azion Console ### Behaviors que se repetem -Quando várias regras correspondem a uma requisição e carregam o mesmo behavior do tipo Set, como _Set Connector_, o behavior não se acumula: só o da última regra correspondente é executado. Por exemplo, uma primeira regra define um Connector para todos os paths, e uma segunda regra define outro Connector para `/api/`. Uma requisição para `/api/` corresponde às duas regras, então o Connector da segunda regra a encaminha. +Quando várias regras correspondentes carregam o mesmo behavior do tipo Set, como _Set Connector_, só o da última regra correspondente é executado. Por exemplo, uma primeira regra define um Connector para todos os paths, e uma segunda regra define outro Connector para `/api/`. Uma requisição para `/api/` corresponde às duas regras, então o Connector da segunda regra a encaminha. _Add Request Header_ também não repete um header: quando duas regras correspondentes adicionam um header com o mesmo nome, a origem o recebe uma vez, com o valor da última dessas regras. @@ -148,7 +156,9 @@ Então, a ordem das regras molda o resultado tanto quanto o conteúdo delas. Uma Alguns behaviors interrompem o processamento de uma requisição, e nada depois deles é executado: nenhum behavior posterior na regra deles e nenhuma regra posterior. _Deny (403 Forbidden)_ responde com uma página `403 Forbidden`, _Deliver_ entrega o conteúdo ao usuário e _Redirect To_ envia o usuário para outra URL com um status `301` ou `302`. _Finish Request Phase_ encerra a Request Phase no ponto em que é executado, então o restante da sua regra e todas as regras posteriores dessa fase são ignorados. -Um behavior que encerra o processamento economiza trabalho e também pode esconder uma regra. No início da lista, ele resolve a requisição antes que as regras seguintes gastem tempo com ela. Colocado antes de uma regra de que você ainda precisa, ele impede que essa regra seja executada em cada requisição à qual a regra anterior corresponde. Com Debug Rules ativo, [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/) e [Data Stream](/pt-br/documentacao/plataforma/data-stream/) mostram quais regras cada requisição executou. Debug Rules é o campo `debug` da Application na API, e [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#debug-rules) mostra onde ativá-lo no Azion Console. +Um behavior que encerra o processamento economiza trabalho e também pode esconder uma regra. No início da lista, ele resolve a requisição antes que as regras seguintes gastem tempo com ela. Colocado antes de uma regra de que você ainda precisa, ele impede que essa regra seja executada em cada requisição à qual a regra anterior corresponde. + +Com Debug Rules ativo, [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/) e [Data Stream](/pt-br/documentacao/plataforma/data-stream/) mostram quais regras cada requisição executou. Debug Rules é o campo `debug` da Application na API, e [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#debug-rules) mostra onde ativá-lo no Azion Console. --- @@ -169,9 +179,9 @@ Uma Application nova tem dois switches ativos, Cache e Functions, e nenhuma regr } ``` -A lista das suas regras de requisição vem vazia, com `count` em `0`. As quatro chaves de `modules` são os quatro switches de uma Application, e [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#recursos-da-plataforma) mostra cada um no Azion Console e na API. Cache não pode ser desativado: a API recusa `false` em `modules.cache.enabled` com `31001`, e, no Azion Console, o switch **Cache** fica travado como ativo, com a nota `Automatically enabled in all accounts.` [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) não é um desses switches: é uma feature de Cache, e cada cache setting a ativa no seu campo `modules.cache.tiered_cache.enabled`. +A lista das suas regras de requisição vem vazia, com `count` em `0`. As quatro chaves de `modules` são os quatro switches de uma Application, e [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#recursos-da-plataforma) mostra cada um no Azion Console e na API. Cache não pode ser desativado: a API recusa `false` em `modules.cache.enabled` com `31001`. [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) não é um desses switches: é uma feature de Cache, e cada cache setting a ativa no seu campo `modules.cache.tiered_cache.enabled`. -Cache está ativo, mas só armazena cópias depois que uma regra aplica um cache setting, e uma Application nova não tem cache settings nem regras. Cache começa a armazenar cópias quando você cria um cache setting e uma regra com _Set Cache Policy_ que o aplica. +Cache está ativo, mas uma Application nova não tem cache settings nem regras. Cache só começa a armazenar cópias quando você cria um cache setting e uma regra com _Set Cache Policy_ que o aplica. Enquanto um switch está desativado, as opções de regra que dependem dele ficam indisponíveis. O formulário do **Rules Engine** no Azion Console marca cada uma dessas opções com _- Required Application Accelerator_, _- Required Image Processor_ ou _- Required Function_, e a API recusa uma regra que usa uma delas. Por exemplo, em uma Application com Application Accelerator desativado, uma regra de requisição com um critério sobre `${request_uri}` retorna `400` com este corpo: @@ -200,7 +210,7 @@ A API aceita a mesma regra com `${uri}` no lugar de `${request_uri}`, porque `${ ## Propagação -Uma alteração em uma Application só chega ao tráfego depois de se propagar pela infraestrutura distribuída da Azion, e a Azion não garante nenhum tempo de propagação. Uma regra nova em uma Application que já atende tráfego pode levar alguns minutos para valer. O deployment de um Workload novo pode levar vários minutos para se propagar e, até lá, o Workload responde com o `404` de placeholder da Azion. +Uma alteração em uma Application só chega ao tráfego depois de se propagar pela infraestrutura distribuída da Azion. A Azion não garante nenhum tempo de propagação. Uma regra nova em uma Application que já atende tráfego pode levar alguns minutos para valer. O deployment de um Workload novo pode levar vários minutos para se propagar e, até lá, o Workload responde com o `404` de placeholder da Azion. Enquanto uma alteração se propaga, as respostas se alternam, porque cada requisição pode chegar a um data center diferente. Uma requisição retorna o `404` de placeholder, e a seguinte retorna a resposta da Application. Uma resposta correta depois de uma alteração não prova que a alteração está no ar, porque a requisição seguinte ainda pode retornar o placeholder. Repita a requisição até que todas as respostas sejam a que você espera. @@ -214,7 +224,7 @@ Um cache armazena uma cópia de uma resposta da origem no data center que a busc Em uma Application, Cache armazena essas cópias, e ele está ativo em toda Application que você cria. Um cache setting pertence a uma Application e guarda os TTLs e as entradas que tornam duas requisições diferentes. Um cache setting só age por meio de uma regra da Request Phase, que aplica esse cache setting com _Set Cache Policy_ às requisições às quais a regra corresponde. _Bypass Cache_ faz o contrário e faz a requisição ignorar o cache. -[Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) lista cada campo e o seu padrão, e [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/) traz o formato completo da key. Para variar o cache por query string, cookie, device group ou método, você precisa de [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/). [Primeiros passos com Cache](/pt-br/documentacao/plataforma/applications/cache/primeiros-passos/) cria um primeiro cache setting e a regra que o aplica. +Para variar o cache por query string, cookie, device group ou método, um cache setting precisa de Application Accelerator ativo na Application. A [visão geral do Cache](/pt-br/documentacao/plataforma/applications/cache/#caminho-da-requisicao) mostra onde Cache age sobre uma requisição, e [Expiração e atualização](/pt-br/documentacao/plataforma/applications/cache/expiracao-e-atualizacao/) explica quanto tempo uma cópia dura e o que a encerra. @@ -224,7 +234,7 @@ A [visão geral do Cache](/pt-br/documentacao/plataforma/applications/cache/#cam Uma cache key construída só a partir da URL supõe que cada URL tem uma única resposta correta. O conteúdo dinâmico quebra essa suposição: sob uma única URL, um visitante autenticado vê o próprio carrinho, uma listagem se reordena quando um filtro muda e o layout difere em um celular. Com uma key construída só a partir da URL, o cache ou entrega a resposta de um visitante a outro, ou não consegue armazenar o path em cache. -Em uma Application, Application Accelerator libera a variação de cache, que remove essa suposição, e mais três capacidades para conteúdo dinâmico. Ele vem desativado em uma Application nova, e cada Application o ativa separadamente, no seu campo `modules.application_accelerator.enabled` na API. Cada cache setting guarda, então, as suas próprias variações, no seu próprio objeto `modules.application_accelerator`. Se você já escreveu um header `Vary` ou uma regra de cache key, o modelo é o mesmo: você lista as entradas que tornam duas requisições diferentes. [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/) lista cada campo, o seu tipo e o seu padrão, e [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#application-accelerator) traz os limites de TTL. Para ativar Application Accelerator e acrescentar uma primeira variação a um cache setting, consulte [Primeiros passos com Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/primeiros-passos/). +Em uma Application, Application Accelerator libera a variação de cache, que remove essa suposição, e mais três capacidades para conteúdo dinâmico. Ele vem desativado em uma Application nova, e cada Application o ativa separadamente, no seu campo `modules.application_accelerator.enabled` na API. Cada cache setting guarda, então, as suas próprias variações, no seu próprio objeto `modules.application_accelerator`. Se você já escreveu um header `Vary` ou uma regra de cache key, o modelo é o mesmo: você lista as entradas que tornam duas requisições diferentes. A [visão geral do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/#caminho-da-requisicao) mostra como uma variação muda a cache key, e [Variação de cache](/pt-br/documentacao/plataforma/applications/application-accelerator/variacao-de-cache/) explica o que ativá-lo libera e quanto custa cada variação. @@ -232,11 +242,13 @@ A [visão geral do Application Accelerator](/pt-br/documentacao/plataforma/appli ## Image Processor -Uma página costuma precisar da mesma imagem em vários tamanhos, recortes e formatos, um para cada layout e browser. Preparar cada variante com antecedência significa um arquivo armazenado por variante e a reconstrução de todos eles sempre que o original muda. Transformar a imagem no momento da requisição evita as duas coisas: a URL descreve a variante, e a plataforma a constrói a partir de um único original quando uma requisição a pede. +Uma página costuma precisar da mesma imagem em vários tamanhos, recortes e formatos, um para cada layout e navegador. Preparar cada variante com antecedência significa um arquivo armazenado por variante e a reconstrução de todos eles sempre que o original muda. Transformar a imagem no momento da requisição evita as duas coisas: a URL descreve a variante, e a plataforma a constrói a partir de um único original quando uma requisição a pede. + +Em uma Application, Image Processor constrói essas variantes. A URL da requisição descreve a variante no parâmetro `ims`, e Image Processor aplica essa descrição à imagem de origem, que fica na origem. Mesmo sem o parâmetro `ims`, Image Processor pode converter a imagem para um formato que o navegador aceita. O resultado, a imagem derivada, é o que o cliente recebe. -Em uma Application, Image Processor constrói essas variantes. A URL da requisição descreve a variante na sua query string `ims`, e Image Processor aplica essa descrição à imagem de origem, que fica na origem. Mesmo sem a query string `ims`, Image Processor pode converter a imagem para um formato que o navegador aceita. O resultado, a imagem derivada, é o que o cliente recebe. Image Processor lê a imagem de origem sem alterá-la e retorna a imagem derivada sem salvá-la como um ativo da conta. Então, um único arquivo na origem atende a cada tamanho, recorte, qualidade e formato que uma página pede. +Image Processor lê a imagem de origem sem alterá-la e retorna a imagem derivada sem salvá-la como um ativo da conta. Então, um único arquivo na origem atende a cada tamanho, recorte, qualidade e formato que uma página pede. -Image Processor vem desativado em uma Application nova, e cada Application o ativa separadamente, no seu campo `modules.image_processor.enabled` na API. Mesmo ativo, Image Processor só age sobre as requisições às quais uma regra da Request Phase com _Optimize Images_ corresponde. [Parâmetros de URL do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/parametros-de-url/) lista as operações que `ims` aceita, e [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/) cobre os headers e os behaviors. Para ativar Image Processor e pedir uma primeira imagem derivada, siga [Primeiros passos com Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/primeiros-passos/). +Image Processor vem desativado em uma Application nova, e cada Application o ativa separadamente, no seu campo `modules.image_processor.enabled` na API. Mesmo ativo, Image Processor só age sobre as requisições às quais uma regra da Request Phase com _Optimize Images_ corresponde. A [visão geral do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/#caminho-da-requisicao) mostra onde Image Processor age sobre uma requisição, e [Entrega de imagens](/pt-br/documentacao/plataforma/applications/image-processor/entrega-de-imagens/) explica como o formato entregue é escolhido e onde Image Processor para. diff --git a/apps/docs/src/content/docs/pt-br/pages/build/applications/glossario.mdx b/apps/docs/src/content/docs/pt-br/pages/build/applications/glossario.mdx index 6cb296bc0b..8088095930 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/applications/glossario.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/applications/glossario.mdx @@ -11,47 +11,47 @@ Definições dos termos que a documentação de [Applications](/pt-br/documentac | Termo | Definição | | --- | --- | | Add Request Header | O behavior do [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) que adiciona um header na forma `Field: value` à requisição, na Request Phase, `add_request_header` na API. Com `Accept: image/webp`, ele faz a conversão automática do Image Processor entregar WEBP a toda requisição à qual a sua regra corresponde. A API recusa o nome `add_header` com `10039 Invalid Choice`. | -| Advanced Cache Key | Uma feature de Application Accelerator que varia a cache key por partes de uma requisição além da URL: a query string, os cookies, os device groups e o método da requisição. Ela exige Application Accelerator ativo na Application, e cada cache setting a configura no seu objeto `modules.application_accelerator`, por meio dos quatro controles Cache vary by. [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#cache-variation) documenta cada controle e onde ele fica no Azion Console e na API. | -| Application | A entidade que executa as suas regras nas requisições recebidas por um [Workload](/pt-br/documentacao/plataforma/workloads/), depois que o deployment desse Workload define essa Application. Uma Application nova começa com Cache e Functions ativos, Application Accelerator e Image Processor desativados e nenhuma regra. No Azion Console, o campo **Application** das **Deployment Settings** de um Workload define essa Application, a API serve as suas Applications em `/v4/workspace/applications`, e [Applications](/pt-br/documentacao/plataforma/applications/) documenta o recurso da plataforma. | -| Application Accelerator | Um recurso da plataforma aninhado em Applications que libera quatro capacidades para o cache e para as regras de uma Application: a variação de cache, o cache de respostas `POST` e `OPTIONS`, um Max Age menor que 60 segundos e os behaviors do Rules Engine que Azion Console marca com _- Required Application Accelerator_, com as variáveis `${request_uri}` e `${device_group}`. Ele vem desativado em uma Application nova, `modules.application_accelerator.enabled` na API, e, com a variação de cache, um cache setting pode acrescentar a query string, os cookies, o device group ou o método da requisição à cache key. [Applications](/pt-br/documentacao/plataforma/applications/#application-accelerator) o descreve, e a [visão geral do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/#caminho-da-requisicao) acompanha uma requisição por ele. | -| behavior | A ação que uma regra executa sobre as requisições às quais os seus critérios correspondem, como _Set Cache Policy_, _Set Connector_ ou _Run Function_. Uma regra executa os seus behaviors na ordem em que os lista, um behavior que encerra o processamento interrompe os behaviors e as regras depois dele na sua fase, e [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) nomeia o recurso da plataforma de que cada behavior precisa. Em um cache setting, `behavior` também é o campo de cada controle Cache vary by, e [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#cache-variation) lista os valores de cada um. | -| Bypass Cache | O behavior do [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/#bypass-cache) que envia à origem uma requisição que corresponde à regra e mantém a resposta fora do cache da Azion, `bypass_cache` na API. Ele roda na Request Phase, exige Application Accelerator, deixa o browser cache a cargo de _Set Cache Policy_ e difere de um TTL de 0 segundos, como [Bypass Cache e um TTL de 0](/pt-br/documentacao/plataforma/applications/application-accelerator/variacao-de-cache/#bypass-cache-e-um-ttl-de-0) explica. Ele age só sobre o cache da Azion, então uma Application com cache settings de Tiered Cache ativos continua armazenando objetos na camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/#bypass-cache) pelo Max Age do cache setting. | -| Cache | Um recurso da plataforma aninhado em Applications que armazena cópias das respostas às requisições recebidas por uma Application, para atender às requisições seguintes pelo mesmo objeto com essas cópias. Cada cópia fica no data center que a armazenou. Ele está sempre ativo em uma Application: a API recusa `modules.cache.enabled` definido como `false` com `31001`, e Azion Console mostra o switch **Cache** travado como ativo, com a nota `Automatically enabled in all accounts.` [Applications](/pt-br/documentacao/plataforma/applications/#cache) o descreve, e a [visão geral do Cache](/pt-br/documentacao/plataforma/applications/cache/#caminho-da-requisicao) acompanha uma requisição por ele. | -| cache key | A entrada de índice sob a qual Cache armazena um objeto, com diferenciação entre maiúsculas e minúsculas. No Cache, a configuração padrão ignora a query string, então a key concatena o scheme, o host e o path, como em `httpsstatic.example.com/page/site.js`, e cada variação acrescenta um valor depois do separador `@@`: sob `allowlist` e `denylist`, esse valor inclui os argumentos de query string que um setting nomeia, mas sob `all`, a query string inteira segue o path, antes de `@@`. Quando o cache setting que serve imagens nomeia `ims` na sua allowlist, a key carrega a query string `ims` depois de `@@`, e uma imagem convertida carrega o seu formato no fim. Sob a configuração padrão, o valor de `ims` não faz parte da key, então todo tamanho e todo processamento do path compartilham uma key, e o primeiro armazenado responde a todo valor de `ims`; [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#formato-da-key) documenta cada forma. | +| Advanced Cache Key | Uma feature de Application Accelerator que varia a cache key por partes de uma requisição além do scheme, do host e do path: a query string, os cookies, os device groups e o método da requisição. Ela exige Application Accelerator ativo na Application, e cada cache setting a configura no seu objeto `modules.application_accelerator`, por meio dos quatro controles Cache vary by. [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#cache-variation) documenta cada controle e onde ele fica no Azion Console e na API. | +| Application | A entidade que processa as requisições recebidas por um [Workload](/pt-br/documentacao/plataforma/workloads/), depois que o deployment desse Workload define essa Application: ela pode executar funções serverless, atuar como proxy reverso para as suas origens ou combinar os dois. Uma Application nova começa com Cache e Functions ativos, Application Accelerator e Image Processor desativados e nenhuma regra. A API serve as suas Applications em `/v4/workspace/applications`, e [Applications](/pt-br/documentacao/plataforma/applications/) documenta o recurso da plataforma. | +| Application Accelerator | Um recurso da plataforma aninhado em Applications que libera quatro capacidades para o cache e para as regras de uma Application: a variação de cache, o cache de respostas `POST` e `OPTIONS`, um Max Age menor que 60 segundos e os behaviors do Rules Engine que Azion Console marca com _- Required Application Accelerator_, com as variáveis `${request_uri}` e `${device_group}`. Ele vem desativado em uma Application nova, `modules.application_accelerator.enabled` na API, e, com a variação de cache, um cache setting pode acrescentar a query string, os cookies, o device group ou o método da requisição à cache key. A [visão geral do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/#caminho-da-requisicao) o descreve e acompanha uma requisição por ele. | +| behavior | A ação que uma regra executa sobre uma requisição, ou sobre uma resposta, que corresponde aos seus critérios, como _Set Cache Policy_, _Set Connector_ ou _Run Function_. Uma regra executa os seus behaviors na ordem em que os lista, um behavior que encerra o processamento interrompe os behaviors e as regras depois dele na sua fase, e [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) nomeia o recurso da plataforma de que cada behavior precisa. Em um cache setting, `behavior` também é o campo de cada controle Cache vary by, e [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#cache-variation) lista os valores de cada um. | +| Bypass Cache | O behavior do [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/#bypass-cache) que envia à origem uma requisição que corresponde à regra e mantém a resposta fora do cache da Azion, `bypass_cache` na API. Ele roda na Request Phase, exige Application Accelerator, deixa o cache do navegador a cargo de _Set Cache Policy_ e difere de um TTL de 0 segundos, como [Bypass Cache e um TTL de 0](/pt-br/documentacao/plataforma/applications/application-accelerator/variacao-de-cache/#bypass-cache-e-um-ttl-de-0) explica. Ele age só sobre o cache da Azion, então uma Application com cache settings de Tiered Cache ativos continua armazenando objetos na camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/#bypass-cache) pelo Max Age do cache setting. | +| Cache | Um recurso da plataforma aninhado em Applications que armazena cópias das respostas às requisições recebidas por uma Application, para atender às requisições seguintes pelo mesmo objeto com essas cópias. Cada cópia fica no data center que a armazenou. Ele está sempre ativo em uma Application: a API recusa `modules.cache.enabled` definido como `false` com `31001`, e Azion Console mostra o switch **Cache** travado como ativo, com a nota `Automatically enabled in all accounts.` A [visão geral do Cache](/pt-br/documentacao/plataforma/applications/cache/#caminho-da-requisicao) o descreve e acompanha uma requisição por ele. | +| cache key | A entrada de índice sob a qual Cache armazena um objeto, com diferenciação entre maiúsculas e minúsculas. A key padrão concatena o scheme, o host e o path, como em `httpsstatic.example.com/page/site.js`, e cada variação que um cache setting ativa acrescenta algo a ela, a maioria depois do separador `@@`. Sob a configuração padrão, o valor de `ims` não faz parte da key, então todo tamanho e todo processamento de um path compartilham uma key; [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#formato-da-key) documenta cada forma, incluindo os casos da query string e de `ims`. | | cache setting | Um conjunto de valores que dizem ao Cache como armazenar e entregar uma resposta: os TTLs do cache da Azion e do navegador, e as entradas que distinguem duas requisições. Um cache setting pertence a uma Application e traz Max Age, stale cache, Large File Optimization e Tiered Cache, além dos quatro controles Cache vary by no seu objeto `modules.application_accelerator`. Ele só age por meio de uma regra que aplica esse cache setting com _Set Cache Policy_ às requisições às quais a regra corresponde; [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) documenta cada campo, e [Primeiros passos com Cache](/pt-br/documentacao/plataforma/applications/cache/primeiros-passos/) cria o primeiro. | -| Connector | A entidade que encaminha as requisições de uma Application à sua origem, depois que uma regra define o ID desse Connector no behavior _Set Connector_. Ela pertence a [Connectors](/pt-br/documentacao/plataforma/connectors/), o recurso da plataforma que substitui as origens que as versões anteriores de Applications configuravam na Application. Com [Load Balancer](/pt-br/documentacao/plataforma/connectors/load-balancer/) ativado, um Connector do tipo `http` pode distribuir o tráfego entre várias origens. | -| critério | Uma condição única dentro de uma regra: uma variável como `${uri}`, um operador de comparação e um argumento quando o operador aceita um, enviados na API como `variable`, `operator`, `conditional` e `argument`. Dentro de um grupo, os critérios se combinam com `and` e `or`, e `and` tem precedência sobre `or`. Os grupos de uma regra se unem por `and`, e a API os carrega como um array de grupos, `[[{...}]]`. [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) lista cada variável e operador. | -| Debug Rules | A configuração de uma Application que registra as regras do Rules Engine que cada requisição executou, `debug` na API e desativada em uma Application nova. Com ela ativa, as regras executadas aparecem no campo `$traceback` em Data Stream e em [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/), e no campo `stacktrace` da [API GraphQL do Real-Time Events](/pt-br/documentacao/devtools/graphql/campos-gql-real-time-events/). [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#debug-rules) mostra onde ativá-la no Azion Console, e [Depure regras criadas com Rules Engine](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/debug-regras/) mostra como ler esses logs. | -| device group | Um nome e uma expressão regular que uma Application compara com o header `User-Agent` de cada requisição. Uma requisição pertence ao grupo quando o header dela corresponde à expressão. Cada device group pertence a uma Application, e uma regra o testa por meio da variável `${device_group}`, que exige Application Accelerator. [Cache vary by Devices](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#cache-variation) varia a cache key por ele, e [Device Groups](/pt-br/documentacao/plataforma/applications/device-groups/) documenta a correspondência. | +| Connector | A entidade que guarda o endereço da sua origem e as configurações que a Azion usa para alcançá-la, e encaminha para ela as requisições de uma Application depois que uma regra define o ID desse Connector no behavior _Set Connector_. Ele pertence a [Connectors](/pt-br/documentacao/plataforma/connectors/), o recurso da plataforma que substitui as origens que as versões anteriores de Applications configuravam na Application. Com [Load Balancer](/pt-br/documentacao/plataforma/connectors/load-balancer/) ativado, um Connector do tipo `http` pode distribuir o tráfego entre várias origens. | +| critério | Uma condição única dentro de uma regra: uma variável como `${uri}`, um operador de comparação e um argumento quando o operador aceita um, enviados na API como `variable`, `operator`, `conditional` e `argument`. Dentro de um grupo, os critérios se combinam com `and` e `or`, com precedência de `and`, enquanto os grupos de uma regra se unem por `and` e vão na API como um array de grupos, `[[{...}]]`. [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) lista cada variável e operador. | +| Debug Rules | A configuração de uma Application que registra as regras do Rules Engine executadas em cada requisição, `debug` na API e desativada em uma Application nova. Com ela ativa, as regras executadas aparecem no campo `$traceback` em Data Stream e em [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/), e no campo `stacktrace` da [API GraphQL do Real-Time Events](/pt-br/documentacao/devtools/graphql/campos-gql-real-time-events/). [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#debug-rules) mostra onde ativá-la no Azion Console, e [Depure regras criadas com Rules Engine](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/debug-regras/) mostra como ler esses logs. | +| device group | Um nome e uma expressão regular que uma Application compara com o header `User-Agent` de cada requisição, e uma requisição pertence ao grupo quando o header dela corresponde à expressão. Cada device group pertence a uma Application, e uma regra o testa por meio da variável `${device_group}`, que exige Application Accelerator. [Cache vary by Devices](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#cache-variation) varia a cache key por ele, e [Device Groups](/pt-br/documentacao/plataforma/applications/device-groups/) documenta a correspondência. | | fase | Um dos dois estágios em que uma Application executa regras: a Request Phase, sobre a requisição antes que exista uma resposta, e a Response Phase, sobre a resposta entregue ao usuário. Você define a fase de uma regra ao criá-la e não pode mudá-la depois, então uma regra na outra fase é uma nova regra. O cache é decidido na Request Phase, e [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) lista as fases em que cada variável e cada behavior estão disponíveis. | | filtro | O componente de `ims` que transforma uma imagem além de um redimensionamento ou de um recorte, escrito `filters:name(argument)`, como em `filters:quality(15)`. Uma string `ims` combina vários filtros, separados por `:`. [Parâmetros de URL do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/parametros-de-url/) documenta `rotate`, `quality`, `watermark`, `format` e `fill`. | | `fit-in` | O prefixo de `ims` que ajusta a imagem derivada dentro de uma caixa `WidthxHeight` e mantém a proporção da imagem de origem, como em `?ims=fit-in/400x400`. Uma imagem menor que a caixa mantém o seu tamanho original. As duas dimensões são opcionais, e [Parâmetros de URL do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/parametros-de-url/#redimensionamento) mostra cada forma. | | Forward Cookies | O behavior do [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) que envia ao usuário o header `Set-Cookie` da origem mesmo quando a resposta vem do cache. Ele roda na Request Phase e exige Application Accelerator. | | Function Instance | A entidade que vincula uma das suas [Functions](/pt-br/documentacao/plataforma/functions/) a uma Application ou a um [Firewall](/pt-br/documentacao/plataforma/firewall/), com os argumentos com que ela roda. A API serve as Function Instances de uma Application em `/v4/workspace/applications//functions`, e uma regra com o behavior _Run Function_ invoca uma Function Instance pelo ID dela em `attributes.value`. [Function Instances](/pt-br/documentacao/plataforma/applications/functions-instances/) documenta os seus campos. | -| Image Processor | Um recurso da plataforma aninhado em Applications que constrói uma imagem nova, a imagem derivada, a partir de uma imagem na origem de uma Application. Ele vem desativado em uma Application nova, e cada Application o ativa separadamente, em `modules.image_processor.enabled` na API ou com `--image-processor` no Azion CLI. [Applications](/pt-br/documentacao/plataforma/applications/#image-processor) o descreve, e a [visão geral do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/#caminho-da-requisicao) acompanha uma requisição por ele. | +| Image Processor | Um recurso da plataforma aninhado em Applications que constrói uma imagem derivada a partir de uma imagem na origem, para as requisições que uma Application recebe. Ele vem desativado em uma Application nova, e cada Application o ativa separadamente, em `modules.image_processor.enabled` na API ou com `--image-processor` na Azion CLI. A [visão geral do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/#caminho-da-requisicao) o descreve e acompanha uma requisição por ele. | | imagem de origem | O arquivo de imagem na origem que Image Processor lê para construir uma imagem derivada. Image Processor o lê sem alterá-lo, e cada transformação produz uma imagem derivada separada. O caminho entre as duas está na [visão geral do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/#caminho-da-requisicao). | | imagem derivada | A imagem que Image Processor constrói a partir da imagem de origem que está na origem. Image Processor a retorna sem salvá-la como um ativo da conta, e a imagem de origem permanece inalterada. A [visão geral do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/#caminho-da-requisicao) descreve como uma requisição produz uma. | | `ims` | O parâmetro de query string que informa a Image Processor qual transformação aplicar, como em `?ims=400x`. Ele pode ficar em qualquer posição da query string, e um valor de `ims` que Image Processor não consegue interpretar retorna a imagem de origem sem transformação. [Parâmetros de URL do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/parametros-de-url/#posicao-do-parametro-ims) documenta cada valor que ele aceita e a sua posição. | | Large File Optimization | Uma feature de Cache que armazena um objeto grande em fragmentos de 1.024 kB, desativada por padrão e ativada por cache setting em `modules.cache.large_file_cache.enabled`. A Azion coloca cada fragmento em cache quando um usuário o requisita, sob a sua própria cache key terminada em `@@bytes=-`, e a feature também se aplica ao Tiered Cache quando essa camada está ativa. [Expiração e atualização](/pt-br/documentacao/plataforma/applications/cache/expiracao-e-atualizacao/#large-file-optimization) descreve o mecanismo. | -| Main Settings | O conjunto de valores que se aplicam a uma Application como um todo: o nome, os recursos da plataforma ativados nela, se ela registra as regras que cada requisição executa e se ela está ativa. Azion Console agrupa esses valores na aba **Main Settings** da Application, em quatro seções: **General**, que traz o nome, **Modules**, **Debug Rules** e **Status**. As configurações de entrega e de protocolo pertencem ao [Workload](/pt-br/documentacao/plataforma/workloads/) que recebe as requisições, e não a Main Settings. [Main Settings de Applications](/pt-br/documentacao/plataforma/applications/main-settings/) documenta cada seção. | +| Main Settings | O conjunto de valores que se aplicam a uma Application como um todo: o nome, os recursos da plataforma ativados nela, se ela registra as regras que cada requisição executa e se ela está ativa. As configurações de entrega e de protocolo pertencem ao [Workload](/pt-br/documentacao/plataforma/workloads/) que recebe as requisições, e não a Main Settings. [Main Settings de Applications](/pt-br/documentacao/plataforma/applications/main-settings/) documenta cada seção. | | Max Age | O campo do cache setting para quantos segundos o cache da Azion mantém uma cópia de um objeto, `modules.cache.max_age` na API, com padrão `60` no Azion Console, na API e na CLI. A API recusa um valor menor que 60 com `21021` enquanto Application Accelerator está desativado, um valor menor que 3 com `21020` enquanto Application Accelerator e Tiered Cache estão ativos e um valor maior que `31536000` com `10068`. O cache do navegador tem um Max Age próprio, `browser_cache.max_age`; [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#application-accelerator) traz os limites que dependem dos recursos da plataforma ativos. | -| `modules` | O objeto da API que traz os switches de uma Application, `application_accelerator`, `cache`, `functions` e `image_processor`, cada um com um valor `enabled`. Azion Console o apresenta como a seção **Modules** de [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#recursos-da-plataforma), cujos **Default Modules** são os mesmos quatro, ao lado de um grupo **Subscription modules** com uma ação **Contact sales**. Tiered Cache não é um desses switches: cada cache setting a ativa no seu próprio campo `modules.cache.tiered_cache.enabled`. | +| `modules` | O objeto da API que traz os switches de uma Application, `application_accelerator`, `cache`, `functions` e `image_processor`, cada um com um valor `enabled`, como documenta [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#recursos-da-plataforma). Tiered Cache não é um desses switches: cada cache setting a ativa no seu próprio campo `modules.cache.tiered_cache.enabled`. | | Optimize Images | O behavior do [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) que aplica Image Processor às requisições que correspondem à sua regra, `optimize_images` na API. Ele roda na Request Phase, não aceita argumentos e exige Image Processor ativo na Application. A API o aceita sozinho em uma regra, sem nenhum _Set Cache Policy_ ao lado. | -| purge por cache key | Um tipo de [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purge-por-cache-key), `cachekey` na API, que remove os objetos armazenados sob cada key de uma lista. Uma key pode nomear uma variação, por query string, cookie ou formato de imagem, então um purge de todas as variações de um objeto lista cada key. É o único tipo de purge que alcança a camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/#purge). | +| purge por cache key | Um tipo de [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purge-por-cache-key), `cachekey` na API, que remove os objetos armazenados sob cada key de uma lista. Uma key pode nomear uma cópia de um objeto que varia por query string, cookie ou formato de imagem, então um purge de todas as cópias do objeto lista cada key. É o único tipo de purge que alcança a camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/#purge). | | purge por URL | Um tipo de [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purge-por-url), `url` na API, que remove o objeto por trás de cada URL de uma lista. Ele não é recursivo, e a Azion converte cada URL na sua cache key sem as variações, então um objeto que varia por cookie, device group ou formato de imagem exige um purge por cache key ou por wildcard. Enviada sem scheme, uma URL remove a cópia em HTTP e a cópia em HTTPS. | | purge por wildcard | Um tipo de [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purge-por-wildcard), `wildcard` na API, que remove todo objeto que corresponde a uma expressão com `*` no path ou na query string. Uma expressão pode ter mais de um `*`, mas uma requisição carrega uma expressão, e a API recusa uma segunda com `10065`. Ele age só sobre o cache da Azion: um purge por wildcard enviado à camada do Tiered Cache é recusado com `30001`. | -| Real-Time Purge | Um recurso da plataforma que remove objetos do Cache ou do Tiered Cache antes do fim do seu TTL. Quando um objeto não está mais no Cache nem no Tiered Cache, a requisição seguinte por esse objeto busca a versão atual na origem. Um purge nomeia os seus objetos por URL, por cache key ou por uma expressão de wildcard, e a Azion o coloca em fila e o lista no histórico de purges quando ele termina. [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/) documenta os três tipos e a camada que cada um alcança. | +| Real-Time Purge | Um recurso da plataforma aninhado em Cache que remove objetos em cache do Cache, ou da camada do Tiered Cache, antes do fim do seu TTL. Quando um objeto não está em nenhuma das camadas, a requisição seguinte por ele busca a versão atual na origem. Um purge nomeia os seus objetos por URL, por cache key ou por uma expressão de wildcard, e [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/) documenta os três tipos, a camada que cada um alcança e como a Azion coloca um purge em fila e o lista no histórico de purges quando ele termina. | | recorte automático | O recorte centralizado que um redimensionamento `WidthxHeight` pode aplicar para que a imagem derivada preencha a caixa solicitada. O recorte é vertical ou horizontal, dependendo de como as dimensões originais se encaixam nas solicitadas, como [Parâmetros de URL do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/parametros-de-url/#redimensionamento) mostra. | | regra | Uma entrada no Rules Engine para Applications que executa os seus behaviors, em uma fase, sobre as requisições às quais os seus critérios correspondem. Cada regra traz um nome e a sua fase, as regras rodam na ordem em que você as organiza, e uma Application nova não tem nenhuma. A API serve as regras da Request Phase em `/v4/workspace/applications//request_rules` e as da Response Phase em `/v4/workspace/applications//response_rules`, e [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) lista os seus campos. | -| Rules Engine para Applications | Uma feature de Applications que contém as regras de uma Application. A Application as executa em ordem como lógica se/então, com os critérios como o se e os behaviors como o então. Azion Console a mostra como a aba **Rules Engine** de cada Application, com as regras agrupadas por fase. [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) documenta cada variável, operador e behavior. | -| Run Function | O behavior do [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) que invoca uma Function Instance nas requisições às quais a sua regra corresponde, `run_function` na API, com o ID da Function Instance em `attributes.value`. Ele roda na Request Phase e na Response Phase, que aceita só Functions escritas em Lua, e exige Functions ativo na Application, `modules.functions.enabled` na API. [Function Instances](/pt-br/documentacao/plataforma/applications/functions-instances/#behavior-run-function) documenta como ele referencia a Function Instance. | +| Rules Engine para Applications | Uma feature de Applications que contém as regras de uma Application. A Application as executa em ordem como lógica se/então, com os critérios como o se e os behaviors como o então. [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) documenta cada variável, operador e behavior. | +| Run Function | O behavior do [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) que invoca uma Function Instance sobre o que corresponde à sua regra, `run_function` na API, com o ID da Function Instance em `attributes.value`. Ele roda na Request Phase e na Response Phase, que aceita só Functions escritas em Lua, e exige Functions ativo na Application, `modules.functions.enabled` na API. [Function Instances](/pt-br/documentacao/plataforma/applications/functions-instances/#behavior-run-function) documenta como ele referencia a Function Instance. | | Set Cache Policy | O behavior do [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/#set-cache-policy) que aplica um cache setting a uma requisição que corresponde à regra, `set_cache_policy` na API, com o ID do cache setting em `attributes.value`. Ele roda na Request Phase e funciona com Application Accelerator ativo ou desativado. Um cache setting só age por meio de uma regra que carrega este behavior, e a API se recusa a excluir um setting em uso com `21014 Cannot Delete Cache Setting`. | -| Set Connector | O behavior do [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) que encaminha as requisições às quais a sua regra corresponde a um [Connector](/pt-br/documentacao/plataforma/connectors/), `set_connector` na API, com o ID do Connector em `attributes.value`. Ele roda na Request Phase, e, quando mais de uma regra correspondente o carrega, só a última roda. | +| Set Connector | O behavior do [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) que envia as requisições às quais a sua regra corresponde a um [Connector](/pt-br/documentacao/plataforma/connectors/), `set_connector` na API, com o ID do Connector em `attributes.value`. Ele roda na Request Phase, e, quando mais de uma regra correspondente o carrega, só a última roda. | | stale cache | Uma feature de Cache que pode responder com uma cópia expirada durante uma janela de stale, quando uma tentativa de revalidação com a origem falha. Cada cache setting a ativa em `modules.cache.stale_cache.enabled`, e a janela é o valor de `stale-while-revalidate` da origem sob _Honor cache policies_, ou 300 segundos sob _Override cache behavior_ ou quando a origem omite a diretiva, como [Expiração e atualização](/pt-br/documentacao/plataforma/applications/cache/expiracao-e-atualizacao/#stale-cache) descreve. | | status de cache | O estado de uma resposta no Cache, no início do header `x-cache`: `HIT`, `MISS`, `EXPIRED`, `STALE`, `UPDATING`, `REVALIDATED` ou `BYPASS`. Uma resposta que a Azion não armazena informa `-` enquanto Application Accelerator está ativo, mas, com ele desativado, uma resposta `GET` ou `HEAD` que não é armazenada informa `MISS`, com `x-cache-expires-in: 0`. [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#status-de-cache) dá o significado de cada um. | -| Tiered Cache | Uma feature de Cache que adiciona uma segunda camada de cache entre o data center que responde a uma requisição e a origem, na região que a topology do cache setting seleciona. A primeira camada é o cache desse data center. Em um miss na primeira camada, o data center consulta a camada do Tiered Cache antes que a requisição siga para a origem, e cada cache setting ativa Tiered Cache no seu próprio campo `modules.cache.tiered_cache.enabled`, em todo plano. O setting precisa usar _Override cache behavior_, ou a API responde `21001`, e, com Application Accelerator ativo, um Max Age de pelo menos 3 segundos; [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) cobre as regiões em que ela roda e o tipo de purge que a limpa. | +| Tiered Cache | Uma feature de Cache que adiciona uma segunda camada de cache, na região que a topology do cache setting seleciona, entre a origem e a primeira camada, que é o cache do data center que responde a uma requisição. Em um miss na primeira camada, o data center consulta a camada do Tiered Cache antes que a requisição siga para a origem, e [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) cobre as regiões em que ela roda e o tipo de purge que a limpa. Cada cache setting ativa Tiered Cache no seu próprio campo `modules.cache.tiered_cache.enabled`, em todo plano, e precisa usar _Override cache behavior_, ou a API responde `21001`, e, com Application Accelerator ativo, um Max Age de pelo menos 3 segundos. | | TTL | Tempo de vida (time to live): o número de segundos que o cache da Azion ou o navegador mantém uma cópia de um objeto. Sob _Honor cache policies_, os headers `Cache-Control` e `Expires` que a origem envia o definem. Quando um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) os substitui, o seu Max Age o define: `modules.cache.max_age` para o cache da Azion e `browser_cache.max_age` para o navegador. | -| variação de cache | Uma cópia adicional de um objeto armazenada sob a sua própria key porque o método da requisição, um argumento de query string, um cookie, um device group, um formato de imagem ou um intervalo de bytes de um arquivo grande difere. Enquanto Application Accelerator está desativado na Application, a API recusa uma variação com `21013`, e isso inclui a variação por query string em `ims` que [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/#variacao-de-cache) descreve. Image Processor processa uma imagem com Application Accelerator ativo ou desativado; [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#cache-variation) documenta os quatro controles. | +| variação de cache | Uma entrada da requisição, além do scheme, do host e do path, que varia a cache key, de modo que cada valor recebe uma cópia separada: o método da requisição, um argumento de query string, um cookie, um device group, um formato de imagem ou um intervalo de bytes de um arquivo grande. Enquanto Application Accelerator está desativado na Application, a API recusa uma variação com `21013`, e isso inclui a variação por query string em `ims` que [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/#variacao-de-cache) descreve. Image Processor processa uma imagem com Application Accelerator ativo ou desativado; [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#cache-variation) documenta os quatro controles. | | variável | Um valor da requisição ou da resposta, escrito `${name}`, que um critério testa ou que um argumento de behavior insere, como `${uri}`, `${host}` ou `${device_group}`. Cada variável está disponível na Request Phase, na Response Phase ou nas duas, como lista [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/#variaveis). Em uma Application, `${request_uri}` exige Application Accelerator, e uma regra que a usa com Application Accelerator desativado é recusada com `25047 Missing Required Modules`, enquanto a mesma regra com `${uri}` é aceita. | | WASM Image Processor | A biblioteca WebAssembly que processa imagens dentro de uma [Function](/pt-br/documentacao/plataforma/functions/), por meio de `loadImage`, `resize`, `getImageResponse` e `clean`, para os formatos `webp`, `jpeg` e `png`. Ela é separada do recurso da plataforma Image Processor: Image Processor transforma uma requisição por meio da query string `ims`, e a biblioteca roda dentro do seu código. [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/#biblioteca-wasm-image-processor) aponta para a sua referência. | | WebSocket Proxy | Uma feature de Applications que transporta uma conexão WebSocket, uma única conexão TCP bidirecional, entre os seus usuários e a sua origem. Uma Application com ela ativa trata uma requisição que carrega `Upgrade: websocket` e `Connection: upgrade` como uma conexão WebSocket e faz proxy dela para a origem, e uma conexão válida responde `101 Switching Protocols`. [WebSocket Proxy](/pt-br/documentacao/plataforma/applications/websocket/) documenta os seus requisitos e a sua disponibilidade. | diff --git a/apps/docs/src/content/docs/pt-br/pages/build/applications/limites.mdx b/apps/docs/src/content/docs/pt-br/pages/build/applications/limites.mdx index 1492f21b47..4498ddad5b 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/applications/limites.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/applications/limites.mdx @@ -10,11 +10,25 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Uma [Application](/pt-br/documentacao/plataforma/applications/) processa as requisições recebidas pelos seus [Workloads](/pt-br/documentacao/plataforma/workloads/): ela executa as suas [regras](/pt-br/documentacao/plataforma/applications/rules-engine/) de requisição e de resposta em cada requisição. Com [WebSocket Proxy](/pt-br/documentacao/plataforma/applications/websocket/) ativado na conta, ela também pode fazer proxy de conexões WebSocket para a origem. Uma Application recebe as requisições de um Workload depois que o deployment desse Workload define essa Application. +Uma [Application](/pt-br/documentacao/plataforma/applications/) processa as requisições recebidas pelos seus [Workloads](/pt-br/documentacao/plataforma/workloads/): ela executa as suas [regras](/pt-br/documentacao/plataforma/applications/rules-engine/) de requisição e de resposta em cada requisição. Cada recurso da plataforma ativado na Application acrescenta limites próprios. [Cache](/pt-br/documentacao/plataforma/applications/cache/) limita os [cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) e os objetos que armazena, e [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/) limita as requisições de purge. [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) move o piso do time to live (TTL) de cache, e [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) limita o tamanho, a largura e a altura de uma imagem. Esta página informa cada limite e a resposta que uma chamada recebe quando a API o recusa. -Um plano de serviço também inclui uma quantidade de uso antes que uma tarifa se aplique. Essa quantidade é um valor de cobrança: ultrapassá-la muda o valor cobrado da conta, e não o que a chamada retorna. A página [Preços da Azion](https://www.azion.com/pt-br/precos/) lista os planos e o uso que cada um inclui. Para as tarifas, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#applications). +Um recurso da plataforma que você ativa pode gerar custos que dependem do uso, e um plano de serviço inclui uma quantidade de uso antes que uma tarifa se aplique. Essa quantidade é um valor de cobrança: ultrapassá-la muda o valor cobrado da conta, e não o que a chamada retorna. A página [Preços da Azion](https://www.azion.com/pt-br/precos/) lista os planos e o uso que cada um inclui. Para as tarifas, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#applications). + +--- + +## Escopo + +Estas restrições valem para toda Application, quaisquer que sejam os recursos da plataforma ativados nela. As restrições de cada recurso da plataforma aninhado abrem a seção desse recurso nesta página. + +- **Fases**: toda regra pertence a uma de duas fases, que você escolhe quando cria a regra e não pode mudar depois. A Request Phase age sobre a requisição antes que exista uma resposta, e a Response Phase age sobre a resposta que o usuário recebe. Somente as regras da Request Phase podem escolher a origem e o cache setting. [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/#fases) lista as variáveis e os behaviors de cada fase e o recurso da plataforma de que cada um precisa. +- **Origens**: uma Application chega a cada origem por meio de um [Connector](/pt-br/documentacao/plataforma/connectors/) que uma regra define, então duas regras com dois Connectors podem encaminhar `/api/` para um servidor e todos os outros paths para outro. A origem por trás de um Connector pode ser um servidor web na sua infraestrutura, um serviço em cloud ou um bucket do [Object Storage](/pt-br/documentacao/plataforma/object-storage/), como mostra [Use um bucket como origem de uma aplicação](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/dados/bucket-como-connector/). Com [Load Balancer](/pt-br/documentacao/plataforma/connectors/load-balancer/) ativado, um Connector do tipo `http` pode distribuir o tráfego entre várias origens. Os Connectors substituem as origens que as versões anteriores de Applications configuravam na Application. +- **Functions**: uma [Function Instance](/pt-br/documentacao/plataforma/applications/functions-instances/) pertence a uma Application, e ela só é executada quando uma regra com _Run Function_ a invoca. Functions começa ativo em uma Application nova, no campo `modules.functions.enabled` dela na API. Somente Functions escritas em Lua são executadas na Response Phase, como informa o formulário da Function Instance no Azion Console: `Only Lua functions can be used in the Response phase.` Para os passos de adicionar a sua primeira Function, consulte [Instancie uma função em uma aplicação](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/instanciar-functions/). +- **Dispositivos**: um [device group](/pt-br/documentacao/plataforma/applications/device-groups/) é um nome e uma expressão regular que a Application compara com o header `User-Agent` de cada requisição. Os dois usos de um grupo precisam de Application Accelerator ativo: uma regra testa o grupo por meio de `${device_group}`, e um cache setting pode manter uma cópia por grupo. [Boas práticas de Applications](/pt-br/documentacao/plataforma/applications/boas-praticas/#defina-um-device-group-pelas-palavras-que-so-esse-dispositivo-envia) mostra como escrever uma expressão que corresponda somente aos dispositivos que você pretende alcançar. +- **WebSocket**: a Azion ativa [WebSocket Proxy](/pt-br/documentacao/plataforma/applications/websocket/) em uma conta somente mediante solicitação, e [Diretrizes de suporte](/pt-br/documentacao/suporte/) explica como pedir. Uma conexão WebSocket abre com os headers `Upgrade: websocket` e `Connection: upgrade`. A Azion recicla as conexões keepalive dos seus servidores aproximadamente a cada 15 minutos, então uma conexão ativa que precisa de mais tempo pode ser encerrada. Quando uma conexão WebSocket se fecha dessa forma, o código do seu cliente precisa detectar a conexão fechada e abri-la de novo. +- **Arquivos grandes**: o mesmo ciclo de keepalive pode encerrar uma transferência longa, e qualquer uma de duas opções permite que cada transferência termine antes que a conexão seja reciclada. Com `modules.cache.large_file_cache.enabled` definido como `true` em um cache setting, Cache armazena o arquivo em fragmentos, como mostra [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#cache). A outra opção, a compressão, reduz o arquivo, como mostra [Comprima as respostas de uma aplicação com gzip](/pt-br/documentacao/guias/performance-e-confiabilidade/otimizacao-de-entrega/gzip-compression/). +- **Workloads**: um Workload guarda os domínios, os protocolos e os certificados que servem a Application, então você configura a entrega no Workload, não na Application. _Redirect HTTP to HTTPS_ só funciona quando o Workload tem HTTPS. Quando o Connector recebe uma resposta 4xx ou 5xx da sua origem, o cliente vê a página de erro do conjunto de custom pages que o deployment do Workload define, em [Custom Pages](/pt-br/documentacao/plataforma/custom-pages/). Para requisitar uma Application no seu próprio domínio a partir de um dispositivo antes de alterar os registros DNS dele, consulte [Teste uma aplicação pelo arquivo hosts](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/testar-edge-application-atraves-do-arquivo-hosts/). --- @@ -40,22 +54,26 @@ Outros três limites se aplicam a nomes: o nome de uma Application aceita de 1 a As 200 regras são um único total que a fase de requisição e a fase de resposta compartilham. Por exemplo, uma Application pode ter 150 regras de requisição e 50 regras de resposta, mas não 200 de cada. -A Azion recicla as conexões keepalive dos seus servidores aproximadamente a cada 15 minutos. Esse ciclo limita por quanto tempo uma conexão entre um usuário e uma Application fica aberta. Uma conexão ativa que precisa de mais tempo pode ser encerrada. Quando uma conexão WebSocket se fecha dessa forma, o código do seu cliente precisa detectar a conexão fechada e abri-la de novo. - -Para um arquivo grande, qualquer uma de duas opções permite que cada transferência termine antes que a conexão seja reciclada. Com `modules.cache.large_file_cache.enabled` definido como `true` em um cache setting, Cache armazena o arquivo em fragmentos de 1.024 kB. A outra opção, a compressão, reduz o arquivo. - -Para armazenar um arquivo grande em fragmentos, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#cache). Para comprimi-lo, consulte [Comprima as respostas de uma aplicação com gzip](/pt-br/documentacao/guias/performance-e-confiabilidade/otimizacao-de-entrega/gzip-compression/). - --- ## Cache -Cache limita um cache setting e um objeto que ele armazena, e Real-Time Purge limita uma requisição de purge. Quando um valor ultrapassa um limite que a API verifica, a chamada retorna HTTP `400` com um código de erro e um título. [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) altera dois limites de um cache setting: o menor TTL que ele aceita e o comportamento de cache que ele permite. - -A API valida os limites de TTL em todo cache setting. +Cache limita um cache setting e um objeto que ele armazena, e Real-Time Purge limita uma requisição de purge. A API valida os limites de TTL em todo cache setting e, quando um valor ultrapassa um limite que ela verifica, a chamada retorna HTTP `400` com um código de erro e um título. [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) altera dois limites de um cache setting: o menor TTL que ele aceita e o comportamento de cache que ele permite. Para as tarifas de Cache, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#cache). Para obter os dados que Tiered Cache transferiu, use o guia [Consulte dados de uso do Tiered Cache](/pt-br/documentacao/guias/plataforma/observabilidade/consultar-dados-de-uso-tiered-cache-com-graphql/). +### Escopo + +Estas restrições valem para Cache em toda Application, a partir de qualquer interface. + +- **Sempre ativo**: Cache fica ativo em toda Application, e a API recusa `false` no campo `modules.cache.enabled` dela com o erro `31001`. No Azion Console, o switch **Cache** de **Main Settings** fica travado como ativo, com a nota `Automatically enabled in all accounts.` Uma Application nova não tem cache settings nem regras, então Cache só armazena cópias quando uma regra com _Set Cache Policy_ aplica um cache setting. +- **Cópias expiradas**: com o stale cache ativado em `modules.cache.stale_cache.enabled` de um cache setting, a Azion pode servir uma cópia expirada quando não consegue confirmar a cópia com a origem, e a resposta então informa `STALE`. Um setting criado pela Azion API ou pela Azion CLI vem com o stale cache desativado, enquanto Azion Console o ativa em um setting novo, como mostra [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#cache). Para saber quando uma página antiga é melhor que um erro, consulte [Boas práticas de Applications](/pt-br/documentacao/plataforma/applications/boas-praticas/#cache). +- **Arquivos grandes**: a Large File Optimization vem desativada em um cache setting novo, e um cache setting a ativa em `modules.cache.large_file_cache.enabled`. Cada fragmento de um arquivo grande é buscado quando um usuário chega a ele e armazenado sob uma key própria, então um purge do arquivo precisa nomear cada fragmento ou usar um wildcard. +- **Tiered Cache**: [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) adiciona uma segunda camada de cache entre o data center que responde a uma requisição e a origem, e exige o behavior `override` e um TTL mínimo. Cada cache setting ativa o Tiered Cache no seu campo `modules.cache.tiered_cache.enabled`, e todos os planos o incluem. Uma regra com _Bypass Cache_ age apenas sobre o cache da Azion, então a camada do Tiered Cache continua a armazenar objetos pelo Max Age do cache setting. +- **Cache keys e variação**: a Azion monta a [cache key](/pt-br/documentacao/plataforma/applications/cache/cache-keys/) padrão a partir do esquema, do host e do path, então um path é um objeto armazenado, e a query string fica fora da key. [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) permite que um cache setting mantenha uma cópia separada para cada valor de um argumento de query string, de um cookie, do device group ou do método. [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) acrescenta à key o formato de uma imagem convertida. +- **Purge**: [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/) coloca um purge em fila depois que você o confirma, porque o resultado leva tempo para se propagar, e o purge aparece no histórico de purges quando termina. Uma cópia que varia por cookie, device group ou formato de imagem sobrevive a um purge por URL, e um purge por cache key ou por wildcard a alcança. +- **Código**: Cache não pode executar código, então o código que lê e grava entradas em cache é executado em uma [Function](/pt-br/documentacao/plataforma/functions/) e chama [Cache API](/pt-br/documentacao/devtools/runtime/api-reference/cache/). + ### Cache settings Cada limite desta tabela se aplica a um cache setting, qualquer que seja a interface que o escreve. A coluna Escopo nomeia o campo da API e, quando existe, o rótulo do Console. A coluna Além do limite traz o código e o título da resposta `400`. Os títulos dos erros mantêm nomes antigos: `Edge Cache` corresponde a Cache, e `Module` corresponde a um recurso da plataforma ativado na Application. @@ -66,7 +84,7 @@ Cada limite desta tabela se aplica a um cache setting, qualquer que seja a inter | TTL mínimo de cache com Tiered Cache ativo | 3 segundos, com Application Accelerator ativo; sem ele, o mínimo de 60 segundos continua valendo | Erro `21020`, `Edge Cache Max Age Lower Than The Minimum Allowed By The Tiered Cache Module`, com `meta.min_value` definido como `3`. | | TTL máximo de cache | 31.536.000 segundos, um ano | Erro `10068`, `Max Value`, com o detalhe `Ensure this value is less than or equal to 31536000.` | | Comportamento de cache com Tiered Cache ativo (`modules.cache.behavior`) | Apenas `override` | Erro `21001`, `It's Not Possible To Use This Edge Cache Behavior.` | -| TTL do browser cache (`browser_cache.max_age`) | 0 a 31.536.000 segundos | Erro `10068`, `Max Value`. | +| TTL do cache do navegador (`browser_cache.max_age`) | 0 a 31.536.000 segundos | Erro `10068`, `Max Value`. | | Nome do cache setting, **Name** (`name`) | 250 caracteres | Erro `10046`, `Max Length`, com o detalhe `Ensure this field has no more than 250 characters.` | Outro limite se aplica a um cache setting: o seu array `cache_vary_by_method` aceita no máximo 2 valores, `post` e `options`. @@ -75,7 +93,7 @@ Com `modules.cache.stale_cache.enabled` definido como `true` em um cache setting ### Objetos em cache -Dois limites se aplicam a um objeto que Cache armazena: o seu tamanho e o tamanho de cada fragmento de um arquivo grande armazenado em partes. A API verifica o tamanho do fragmento em todo cache setting. +Dois limites se aplicam a um objeto em cache: o seu tamanho e o tamanho de cada fragmento de um arquivo grande. A API verifica o tamanho do fragmento em todo cache setting. | Escopo | Limite | Além do limite | | --- | --- | --- | @@ -113,6 +131,18 @@ Application Accelerator altera um limite de um cache setting: o menor tempo que Para as tarifas de Application Accelerator, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#application-accelerator). +### Escopo + +Estas restrições valem para Application Accelerator em toda Application, a partir de qualquer interface. + +- **Uma Application de cada vez**: Application Accelerator vem desativado em uma Application nova e pertence à Application, então uma Application pode tê-lo ativo enquanto outra o tem desativado. Ativá-lo mantém o tráfego como estava: os controles de variação de um cache setting começam em `ignore`, e um cache setting só alcança uma requisição por meio de uma regra com [Set Cache Policy](/pt-br/documentacao/plataforma/applications/rules-engine/#set-cache-policy). [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#recursos-da-plataforma) mostra onde ativá-lo no Azion Console e na API. +- **Tudo ou nada**: uma Application recebe todas as capacidades que Application Accelerator libera, ou nenhuma delas. Elas são a variação de cache, o cache de respostas `POST` e `OPTIONS`, um piso mais baixo para o Max Age, as variáveis `${request_uri}` e `${device_group}` e os behaviors do Rules Engine que [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/) lista. +- **Métodos**: uma Application repassa requisições `POST`, `PUT`, `PATCH`, `DELETE` e `OPTIONS` à origem com ou sem Application Accelerator. Desses métodos, Application Accelerator permite armazenar em cache só as respostas `POST` e `OPTIONS`. Um `POST` informa `-` em `x-cache` até que o campo `cache_vary_by_method` do cache setting traga `post`. +- **Tamanho da variação**: cada valor distinto de uma entrada variada é um objeto em cache separado. Um cookie único para cada visitante dá uma cópia a cada visitante, então o número de objetos cresce com a audiência, e não com o conteúdo. Uma allowlist e a ordenação, o campo `sort_enabled`, limitam esse número, como explica [Variação de cache](/pt-br/documentacao/plataforma/applications/application-accelerator/variacao-de-cache/#o-custo-de-uma-variacao). Para as práticas, consulte [Boas práticas de Applications](/pt-br/documentacao/plataforma/applications/boas-praticas/#application-accelerator). +- **Purges**: as cópias que variam por cookie ou por device group sobrevivem a um purge por URL, e um purge por cache key ou um purge por wildcard que termina a key com `@@*` as alcança. As cópias que variam por query string são a exceção: um purge por URL as alcança quando envia os argumentos na ordem em que foram apresentados, ou em ordem alfabética com `sort_enabled` ativo. Para os tipos de purge, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purgue-conteudo-que-varia). +- **Bypass Cache e um TTL de 0**: [Bypass Cache](/pt-br/documentacao/plataforma/applications/rules-engine/#bypass-cache) envia à origem cada requisição que corresponde à sua regra e mantém a resposta fora do cache da Azion, mas não fora da camada do Tiered Cache de um cache setting que ativa o Tiered Cache. Um Max Age de 0 segundos mantém a requisição no caminho do cache, e toda requisição ainda chega à origem. [Bypass Cache e um TTL de 0](/pt-br/documentacao/plataforma/applications/application-accelerator/variacao-de-cache/#bypass-cache-e-um-ttl-de-0) compara como os dois tratam uma requisição. +- **Image Processor**: para variar o cache pela string `ims` do [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/), acrescente `ims` à allowlist de query string do cache setting que entrega as imagens. + ### Limites padrão Cada linha nomeia um limite de TTL de cache e a condição que o coloca em vigor. @@ -126,9 +156,9 @@ Cada linha nomeia um limite de TTL de cache e a condição que o coloca em vigor Um Max Age menor que o mínimo em vigor retorna HTTP `400`. O erro é `21021` enquanto Application Accelerator está desativado, e `21020` enquanto Application Accelerator e Tiered Cache estão ambos ativos. Um valor maior que o máximo retorna o erro `10068`. Para os títulos dos erros, consulte [Cache settings](#cache-settings). -Para saber como um Max Age de 0 segundos e o behavior _Bypass Cache_ tratam uma requisição, consulte [Bypass Cache e um TTL de 0](/pt-br/documentacao/plataforma/applications/application-accelerator/variacao-de-cache/#bypass-cache-e-um-ttl-de-0). +Uma requisição que Application Accelerator varia continua limitada pelos recursos da plataforma que armazenam o objeto e executam código sobre ele. Cache limita o próprio objeto: o tamanho de um objeto em cache e o tamanho de cada fragmento de um arquivo grande. Para esses valores, consulte [Objetos em cache](#objetos-em-cache). -Uma requisição que Application Accelerator varia continua limitada pelos recursos da plataforma que armazenam o objeto e executam código sobre ele. Cache limita o próprio objeto: o tamanho de um objeto em cache e o tamanho de cada fragmento de um arquivo grande. Para esses valores, consulte [Objetos em cache](#objetos-em-cache). Uma [Function](/pt-br/documentacao/plataforma/functions/) que a Application executa tem os seus próprios limites de código e de cada invocação. Para esses valores, consulte [Limites de Functions](/pt-br/documentacao/plataforma/functions/limites/). +Uma [Function](/pt-br/documentacao/plataforma/functions/) que a Application executa tem os seus próprios limites de código e de cada invocação. Para esses valores, consulte [Limites de Functions](/pt-br/documentacao/plataforma/functions/limites/). --- @@ -138,9 +168,18 @@ Image Processor limita uma única imagem com três limites padrão: o seu tamanh Para as tarifas da métrica Images, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#image-processor). Para obter o número de imagens que a conta processou, use o guia [Consulte dados de uso do Image Processor](/pt-br/documentacao/guias/plataforma/observabilidade/consultar-dados-de-uso-image-processor-com-graphql/). +### Escopo + +Estas restrições valem para Image Processor em toda Application, a partir de qualquer interface. + +- **Uma Application de cada vez**: Image Processor vem desativado em uma Application nova, e cada Application o ativa separadamente, no seu campo `modules.image_processor.enabled` na API. Mesmo ativo, Image Processor processa somente as requisições às quais uma regra com _Optimize Images_ corresponde. [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#recursos-da-plataforma) mostra onde ativá-lo no Azion Console e na API. +- **Parâmetros que ele não interpreta**: um valor de `ims` que Image Processor não consegue interpretar retorna a imagem de origem sem transformação. Para a sintaxe que cada operação aceita, consulte [Parâmetros de URL](/pt-br/documentacao/plataforma/applications/image-processor/parametros-de-url/). +- **Armazenamento**: Image Processor retorna cada imagem derivada sem salvá-la como um ativo da conta, e não é possível fazer upload de imagens para Image Processor. O cache guarda as imagens derivadas, e a imagem de origem permanece onde já está. Um workflow que precisa manter um arquivo transformado salva a resposta por conta própria. +- **Código**: [WASM Image Processor](/pt-br/documentacao/devtools/azion-lib/wasm-image-processor/) é uma biblioteca WebAssembly que processa imagens dentro de uma [Function](/pt-br/documentacao/plataforma/functions/). Ela é executada no código dessa Function, separada de Image Processor e das configurações dele, como explica [Onde Image Processor para](/pt-br/documentacao/plataforma/applications/image-processor/entrega-de-imagens/#onde-image-processor-para). + ### Limites padrão -Image Processor aplica três limites padrão a uma imagem: um tamanho máximo de 150 MB, uma largura máxima de 3.840 pixels e uma altura máxima de 2.160 pixels. +Uma imagem aceita no máximo 150 MB, 3.840 pixels de largura e 2.160 pixels de altura. Cada parâmetro `ims` também aceita uma faixa de valores própria. Para a faixa de cada parâmetro, consulte [Parâmetros de URL](/pt-br/documentacao/plataforma/applications/image-processor/parametros-de-url/). diff --git a/apps/docs/src/content/docs/pt-br/pages/build/applications/solucao-de-problemas.mdx b/apps/docs/src/content/docs/pt-br/pages/build/applications/solucao-de-problemas.mdx index cea04bc329..e0f44fed62 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/applications/solucao-de-problemas.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/applications/solucao-de-problemas.mdx @@ -51,7 +51,7 @@ Uma regra age apenas sobre as requisições que correspondem aos seus critérios - **Os critérios não correspondem à requisição**: [Critérios](/pt-br/documentacao/plataforma/applications/rules-engine/#criterios) lista cada variável, operador e condicional. - **Uma regra anterior encerrou o processamento**: um behavior como _Deny (403 Forbidden)_ interrompe os behaviors e as regras depois dele, como explica [Como as regras são executadas](/pt-br/documentacao/plataforma/applications/como-funciona/#como-as-regras-sao-executadas). -Para distinguir as três, verifique quais regras rodaram na requisição. Debug Rules registra as regras do Rules Engine que rodam em cada requisição, e ele vem desativado em uma Application nova. +Para distinguir as três, verifique quais regras rodaram na requisição. Debug Rules, a configuração de uma Application que registra as regras do Rules Engine executadas em cada requisição, vem desativada em uma Application nova. - **Ative Debug Rules**: no Azion Console, na aba **Main Settings** da Application, ative **Debug Rules** e selecione **Save**. Pela API, defina o campo `debug` da Application como `true`. - **Leia as regras que rodaram**: o campo `$traceback` de cada log as lista, como descreve [Debug Rules](/pt-br/documentacao/plataforma/applications/main-settings/#debug-rules). Uma regra ausente do log de uma requisição não rodou nela: refaça os critérios dela, ou mova-a para antes da regra que encerrou o processamento. @@ -77,9 +77,9 @@ As métricas e os logs então mostram quais requisições, paths ou períodos ca ## Uma regra é recusada com Missing Required Modules -Salvar uma regra de requisição que lê `${request_uri}` falha com `400` e o código `25047` enquanto Application Accelerator está desativado, como [Erros](/pt-br/documentacao/plataforma/applications/rules-engine/#erros) mostra por completo. +Salvar uma regra de requisição que lê `${request_uri}` falha com `400`, o código `25047` e `Missing Required Modules` enquanto Application Accelerator está desativado, como [Erros](/pt-br/documentacao/plataforma/applications/rules-engine/#erros) mostra por completo. -Algumas variáveis e alguns behaviors pertencem a um recurso da plataforma, e a API recusa uma regra que use um deles enquanto esse recurso da plataforma estiver desativado: `meta.missing_required_modules` nomeia o recurso da plataforma. +Algumas variáveis e alguns behaviors exigem um recurso da plataforma ativado na Application, e a API recusa uma regra que use um deles enquanto esse recurso da plataforma estiver desativado: `meta.missing_required_modules` nomeia o recurso da plataforma. - **Use `${uri}` no critério em vez disso**: ele não exige nenhum recurso da plataforma, então a mesma regra retorna `202`, como [Variáveis](/pt-br/documentacao/plataforma/applications/rules-engine/#variaveis) lista para cada variável. - **Ative o recurso da plataforma que o erro nomeia**: no Azion Console, o switch dele fica na seção **Modules** da aba **Main Settings** da Application, e **Save** o aplica. [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#recursos-da-plataforma) informa a flag da Azion CLI e a key da API dele. @@ -90,7 +90,7 @@ Com Application Accelerator ativado, a regra com `${request_uri}` é aceita. ## Um behavior é recusado com Invalid Choice -O corpo de uma regra copiado de um exemplo mais antigo falha com `400`, o código `10039` e `Invalid Choice`, que [Erros](/pt-br/documentacao/plataforma/applications/rules-engine/#erros) lista com o detalhe e o ponteiro. +O corpo de uma regra copiado de um exemplo mais antigo falha com `400`, o código `10039` e `Invalid Choice`. [Erros](/pt-br/documentacao/plataforma/applications/rules-engine/#erros) lista esse erro com o detalhe e o ponteiro. A API aceita apenas os tipos de behavior que ela define. O que adiciona um header à requisição é `add_request_header`, _Add Request Header_ no Azion Console, e não `add_header`. @@ -159,7 +159,7 @@ As respostas ao método armazenado em cache então trazem um status, e uma key q As requisições às quais uma regra com _Bypass Cache_ corresponde continuam recebendo uma cópia armazenada, e a origem não as vê. -_Bypass Cache_ impede que o cache da Azion armazene a resposta, mas a camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/#bypass-cache) fica fora do seu alcance. Enquanto um cache setting mantém Tiered Cache ativado, essa camada continua armazenando objetos pelo Max Age do cache setting e responde antes da origem. +_Bypass Cache_ envia à origem as requisições às quais a sua regra corresponde e mantém a resposta fora do cache da Azion, mas a camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/#bypass-cache) fica fora do seu alcance. Enquanto um cache setting mantém Tiered Cache ativado, essa camada continua armazenando objetos pelo Max Age do cache setting e responde antes da origem. - **Desative Tiered Cache**: no Azion Console, na seção **Cache** do cache setting que atende o path. Pela API, defina `modules.cache.tiered_cache.enabled` como `false` nesse setting. - **Purgue as duas camadas, a do Tiered Cache primeiro**: purgue Tiered Cache por cache key e depois Cache, para que a primeira camada não se encha de novo com uma cópia desatualizada, como mostra [Purgue conteúdo em cache](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/purgar-conteudo-em-cache/). @@ -178,16 +178,16 @@ Uma cópia armazenada fica em cache até o fim do seu TTL ou até que um purge a Na sua requisição seguinte, a URL purgada informa `x-cache: MISS`, e a resposta traz a nova versão. -### Um purge não expirou uma variação do objeto +### Um purge não expirou uma cópia do objeto O purge foi aceito, mas alguns visitantes, ou algumas query strings, continuam recebendo o conteúdo antigo. -Um purge por URL mapeia cada URL para uma única cache key sem variação, então as cópias que variam por cookie, device group ou formato de imagem sobrevivem a ele, por mais que você o repita. Ele alcança uma variação por query string apenas quando a URL lista os argumentos na ordem em que a key os armazena, alfabética quando a variação tem `sort_enabled` definido como `true`. +Um purge por URL mapeia cada URL para uma única cache key sem variação, então as cópias que variam por cookie, device group ou formato de imagem sobrevivem a ele, por mais que você o repita. Ele alcança uma cópia que varia por query string apenas quando a URL lista os argumentos na ordem em que a key os armazena, alfabética quando a variação por query string tem `sort_enabled` definido como `true`. -- **Purgue por cache key**: liste cada variação do objeto, no máximo 50 keys em uma requisição, cada uma copiada do header `x-cache-key` da sua resposta. -- **Purgue por wildcard**: termine a expressão com `@@*` para as variações que acrescentam o separador `@@`, como as por cookie e por device group, ou com `?*` para as variações por query string. +- **Purgue por cache key**: liste a key de cada cópia do objeto, no máximo 50 keys em uma requisição, cada uma copiada do header `x-cache-key` da sua resposta. +- **Purgue por wildcard**: termine a expressão com `@@*` para as cópias cuja variação acrescenta o separador `@@`, como as variações por cookie e por device group, ou com `?*` para as cópias que variam por query string. -Na sua requisição seguinte, cada variação purgada informa `x-cache: MISS`, como [Purgue conteúdo que varia](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purgue-conteudo-que-varia) mostra para cada tipo de variação. +Na sua requisição seguinte, cada cópia purgada informa `x-cache: MISS`, como [Purgue conteúdo que varia](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purgue-conteudo-que-varia) mostra para cada tipo de variação. ### Um Max Age menor que 60 segundos é recusado com o erro 21021 @@ -202,7 +202,7 @@ O cache setting então é aceito, dentro dos limites que [Limites de Application ### Tiered Cache não pode ser ativado e a API retorna 21001 ou 21020 -Um cache setting que envia `tiered_cache.enabled` como `true` é recusado com `400`: o código `21001` responde ao comportamento de cache `honor`, e o código `21020` a um Max Age menor que 3 segundos, como [Erros](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros) detalha para cada um. +Um cache setting que envia `tiered_cache.enabled` como `true` é recusado com `400` e o código `21001` ou `21020`. O código `21001` responde ao comportamento de cache `honor`, e o código `21020` responde a um Max Age menor que 3 segundos, como [Erros](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros) detalha para cada um. Tiered Cache exige o _Override cache behavior_ no Azion Console, `override` na API, e um Max Age de pelo menos 3 segundos. Com Application Accelerator desativado, o piso de 60 segundos do erro `21021` se aplica primeiro, então de 3 a 59 segundos continua sendo recusado. @@ -211,12 +211,24 @@ Tiered Cache exige o _Override cache behavior_ no Azion Console, `override` na A ```bash cat > cache-setting.json <<'EOF' -{"name":"tiered-from-file","modules":{"cache":{"behavior":"override","max_age":600,"tiered_cache":{"enabled":true,"topology":"nearest-region"}}}} +{ + "name": "tiered-from-file", + "modules": { + "cache": { + "behavior": "override", + "max_age": 600, + "tiered_cache": { + "enabled": true, + "topology": "nearest-region" + } + } + } +} EOF azion create cache-setting --application-id --file cache-setting.json ``` -A CLI imprime `Created Cache Settings configuration with ID `, e o setting é lido de volta com `enabled` igual a `true` em `tiered_cache`. Para as topologias, consulte [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/). +Substitua `` pelo ID da sua Application. A CLI imprime `Created Cache Settings configuration with ID `, e o setting é lido de volta com `enabled` igual a `true` em `tiered_cache`. Para as topologias, consulte [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/). ### Um cache setting não pode ser excluído e a API retorna 21014 @@ -231,7 +243,7 @@ O behavior _Set Cache Policy_ de alguma regra ainda aplica o setting, e um setti azion delete cache-setting --application-id --cache-setting-id --format json ``` -Sem nenhuma regra que aplique o setting, a CLI imprime `{"message": "Caches settings configuration was successfully deleted"}`, e o setting sai da lista de **Cache Settings** no Azion Console. +Substitua `` pelo ID da sua Application e `` pelo ID do setting. Sem nenhuma regra que aplique o setting, a CLI imprime `{"message": "Caches settings configuration was successfully deleted"}`, e o setting sai da lista de **Cache Settings** no Azion Console. ### Uma requisição de purge é rejeitada com 30001, 30003 ou 30005 @@ -249,7 +261,7 @@ Azion CLI informa `30001` com o detalhe da API, como mostra este purge por URL n azion purge --urls "https:///" --layer tiered_cache ``` -O comando imprime `Error: ["Invalid purge layer for purge type \"url\"."]`. Um purge por cache key na mesma camada imprime `Purge carried out successfully`, e os purges aceitos retornam `201` com `state` igual a `executed`, como mostra [Corpo da requisição](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#corpo-da-requisicao). +Aqui, `` e `` representam um domínio da sua conta e um path nele. O comando imprime `Error: ["Invalid purge layer for purge type \"url\"."]`. Um purge por cache key na mesma camada imprime `Purge carried out successfully`, e os purges aceitos retornam `201` com `state` igual a `executed`, como mostra [Corpo da requisição](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#corpo-da-requisicao). ### Azion CLI imprime um objeto de erro vazio @@ -266,38 +278,38 @@ A saída simples então mostra por que a API recusou a requisição, e a requisi ## Application Accelerator -Application Accelerator libera quatro capacidades para o cache e para as regras de uma Application: a variação de cache, o cache de respostas `POST` e `OPTIONS`, um Max Age menor que 60 segundos e mais behaviors e variáveis do Rules Engine. Ele vem desativado em uma Application nova. Para saber como uma variação altera a key, consulte a [visão geral do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/#caminho-da-requisicao). +Application Accelerator libera quatro capacidades para o cache e para as regras de uma Application. Elas são a variação de cache, o cache de respostas `POST` e `OPTIONS`, um Max Age menor que 60 segundos e mais behaviors e variáveis do Rules Engine. Ele vem desativado em uma Application nova. Para saber como uma variação altera a key, consulte a [visão geral do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/#caminho-da-requisicao). ### Uma requisição POST não informa status de cache -Um `POST` informa `-` em `x-cache` até que Application Accelerator esteja ativado e o cache setting armazene o método em cache: _POST_ em **Cache vary by Method** no Azion Console, ou `post` em `cache_vary_by_method` na API. [HTTP methods](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#http-methods) mostra o campo para cada interface. Para a correção, consulte [O header x-cache informa um traço em cada resposta de um path](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#o-header-x-cache-informa-um-traco-em-cada-resposta-de-um-path). +Um `POST` informa `-` em `x-cache` até que Application Accelerator esteja ativado e o cache setting armazene o método em cache. O setting recebe _POST_ em **Cache vary by Method** no Azion Console, ou `post` em `cache_vary_by_method` na API. [HTTP methods](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#http-methods) mostra o campo para cada interface. Para a correção, consulte [O header x-cache informa um traço em cada resposta de um path](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#o-header-x-cache-informa-um-traco-em-cada-resposta-de-um-path). -### Variações por cookie e por device group sobrevivem a um purge +### Cópias que variam por cookie ou por device group sobrevivem a um purge -Essas variações vêm do objeto `modules.application_accelerator` do cache setting, a seção **Application Accelerator** no Azion Console. Cada uma é um objeto sob a sua própria key, fora do alcance de um purge por URL. Para o purge por cache key ou pelo wildcard `@@*` que as alcança, consulte [Um purge não expirou uma variação do objeto](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#um-purge-nao-expirou-uma-variacao-do-objeto). +As variações por cookie e por device group vêm do objeto `modules.application_accelerator` do cache setting, a seção **Application Accelerator** no Azion Console. Cada cópia que elas produzem é um objeto sob a sua própria key, fora do alcance de um purge por URL. Para o purge por cache key ou pelo wildcard `@@*` que a alcança, consulte [Um purge não expirou uma cópia do objeto](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#um-purge-nao-expirou-uma-copia-do-objeto). -### Um purge por URL não alcança uma variação por query string +### Um purge por URL não alcança uma cópia que varia por query string -Um purge por URL alcança uma variação por query string apenas quando lista os argumentos pelos quais a key varia, na ordem em que a key os armazena. Essa ordem é alfabética quando **Sort** está ativado em **Cache vary by Query String** no Azion Console, `sort_enabled` na API. Para esse purge e o wildcard `?*`, consulte [Um purge não expirou uma variação do objeto](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#um-purge-nao-expirou-uma-variacao-do-objeto). +Um purge por URL só alcança essa cópia quando lista os argumentos da key na ordem em que a key os armazena. Essa ordem é alfabética quando **Sort** está ativado em **Cache vary by Query String** no Azion Console, `sort_enabled` na API. Para esse purge e o wildcard `?*`, consulte [Um purge não expirou uma cópia do objeto](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#um-purge-nao-expirou-uma-copia-do-objeto). ### Um behavior ou uma variável não pode ser selecionado no Rules Engine -No Azion Console, na aba **Rules Engine** de uma Application, um behavior como _Bypass Cache_, _Forward Cookies_ ou _Rewrite Request_ não pode ser adicionado a uma regra. Na lista, o nome dele termina com `- Required Application Accelerator`, e a variável `${device_group}` não está disponível nos critérios. +Um behavior como _Bypass Cache_, _Forward Cookies_ ou _Rewrite Request_ não pode ser adicionado a uma regra. No Azion Console, na aba **Rules Engine** de uma Application, o nome dele termina com `- Required Application Accelerator`, e a variável `${device_group}` não está disponível nos critérios. -Seis behaviors e a variável `${device_group}` ficam bloqueados enquanto Application Accelerator está desativado na Application. +Oito behaviors e as variáveis `${request_uri}` e `${device_group}` exigem Application Accelerator ativado na Application. - **Ative Application Accelerator**: no Azion Console, o switch fica em **Main Settings** › **Modules**. - **Ative Functions para Run Function**: _Run Function_ depende de [Functions](/pt-br/documentacao/plataforma/functions/) ativado na Application, e não de Application Accelerator, como explica [Run Function não aparece na lista de comportamentos](/pt-br/documentacao/plataforma/functions/solucao-de-problemas/#run-function-nao-aparece-na-lista-de-comportamentos). -Uma regra então pode receber os seis behaviors, e os critérios dela podem usar `${device_group}`, como [Behaviors do Rules Engine](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#behaviors-do-rules-engine) lista por fase. +Uma regra então pode receber os oito behaviors, e os critérios dela podem usar `${request_uri}` e `${device_group}`, como [Behaviors do Rules Engine](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#behaviors-do-rules-engine) lista por fase. ### O conteúdo é entregue do cache com Bypass Cache configurado -_Bypass Cache_ exige Application Accelerator, e uma requisição a que uma regra com _Bypass Cache_ corresponde ainda pode ser respondida pela camada do Tiered Cache, que [Bypass Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/#bypass-cache) não alcança. A regra funciona, então alterá-la não corrige nada: desative Tiered Cache e purgue as duas camadas, como descreve [O conteúdo continua sendo entregue do cache depois de uma regra com Bypass Cache](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#o-conteudo-continua-sendo-entregue-do-cache-depois-de-uma-regra-com-bypass-cache). +_Bypass Cache_ exige Application Accelerator. Uma requisição a que uma regra com _Bypass Cache_ corresponde ainda pode ser respondida pela camada do Tiered Cache, que [Bypass Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/#bypass-cache) não alcança. A regra funciona, então alterá-la não corrige nada: desative Tiered Cache e purgue as duas camadas, como descreve [O conteúdo continua sendo entregue do cache depois de uma regra com Bypass Cache](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#o-conteudo-continua-sendo-entregue-do-cache-depois-de-uma-regra-com-bypass-cache). ### Uma variação de cache é recusada com o erro 21013 -Salvar um cache setting retorna `400` e o código `21013` quando ele define uma variação na sua seção **Application Accelerator** no Azion Console, ou um `behavior` diferente de `ignore` ou um método em `modules.application_accelerator` na API. [Erros](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros) detalha o código. +Salvar um cache setting retorna `400` e o código `21013` quando o setting varia a key. No Azion Console, isso é uma variação na sua seção **Application Accelerator** e, na API, um `behavior` diferente de `ignore` ou um método em `modules.application_accelerator`. [Erros](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros) detalha o código. Uma variação de cache por método, query string, cookie ou device group exige Application Accelerator. @@ -308,7 +320,7 @@ O setting então é salvo, e a sua variação é lida de volta como foi enviada. ### Uma variação por query string é recusada com o erro 21018 -Um cache setting cujo comportamento de query string é `allowlist` ou `denylist`, enviado com uma lista de campos vazia, retorna `400` e o código `21018`, como [Erros](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros) detalha. +Um cache setting com `allowlist` ou `denylist` na query string e uma lista de campos vazia retorna `400` e o código `21018`, como [Erros](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#erros) detalha. `allowlist` nomeia os campos pelos quais a key varia, e `denylist` nomeia os que ela deixa de fora. Cada um precisa de pelo menos um, e Azion Console torna **Fields** obrigatório. @@ -321,11 +333,11 @@ O setting então é salvo, com `cache_vary_by_querystring` guardando o que você ## Image Processor -Image Processor constrói uma imagem derivada a partir da imagem de origem quando uma regra aplica _Optimize Images_, e ele vem desativado em uma Application nova. Para o caminho da imagem de origem até a imagem derivada, consulte a [visão geral do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/#caminho-da-requisicao). +Image Processor constrói uma imagem derivada a partir da imagem de origem quando uma regra aplica _Optimize Images_. Ele vem desativado em uma Application nova. Para o caminho da imagem de origem até a imagem derivada, consulte a [visão geral do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/#caminho-da-requisicao). ### A imagem volta sem transformação, embora x-ims informe Enabled -Uma requisição com uma query string `ims` retorna a imagem de origem como ela é, e a resposta traz `x-ims: Enabled`. +Uma requisição com o parâmetro `ims` retorna a imagem de origem como ela é, e a resposta traz `x-ims: Enabled`. Image Processor não consegue interpretar o valor de `ims`, como `450xOrig`, então retorna a imagem de origem sem transformação. `ims` pode ficar em qualquer posição da query string, então só o valor dele decide o resultado. @@ -335,9 +347,9 @@ A URL então retorna a imagem derivada, com a transformação que o valor de `im ### A imagem é entregue sem processamento e a sua query string ims é ignorada -A query string `ims` de uma requisição é válida, mas a imagem de origem volta como está, sem redimensionamento, recorte ou filtro. +O parâmetro `ims` de uma requisição é válido, mas a imagem de origem volta como está, sem redimensionamento, recorte ou filtro. -Uma transformação só começa quando uma regra corresponde à requisição e aplica _Optimize Images_, qualquer que seja o pedido da query string `ims`. +Uma transformação só começa quando uma regra corresponde à requisição e aplica _Optimize Images_, qualquer que seja o pedido do parâmetro `ims`. - **Verifique a que a regra corresponde**: no Azion Console, na aba **Rules Engine** da Application, compare o critério da regra com a requisição. Um critério para imagens compara `${uri}`, ou `${request_uri}` com Application Accelerator ativado, por meio de `matches` com um argumento como `\.(jpg|jpeg|gif|bmp|png|ico|webp|avif)`. - **Verifique o behavior**: _Optimize Images_ precisa ser um behavior da Request Phase da regra. Quando a regra também armazena o resultado em cache, _Set Cache Policy_ fica ao lado dele, como descreve [Behaviors do Rules Engine](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/#behaviors-do-rules-engine). @@ -364,7 +376,7 @@ Um filtro `filters:format()` retorna o formato que nomeia, qualquer que seja o h - **Verifique a que a regra corresponde quando a resposta não tem `x-ims`**: nenhuma regra com _Optimize Images_ corresponde à requisição. [A imagem é entregue sem processamento e a sua query string ims é ignorada](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#a-imagem-e-entregue-sem-processamento-e-a-sua-query-string-ims-e-ignorada) mostra a que a regra precisa corresponder. - **Verifique o valor de `ims` quando a resposta traz `x-ims: Enabled`**: Image Processor não consegue interpretar o valor, como descreve [A imagem volta sem transformação, embora x-ims informe Enabled](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#a-imagem-volta-sem-transformacao-embora-x-ims-informe-enabled). -As requisições correspondentes então recebem a imagem como `image/webp` ou `image/avif`, o formato que a string `ims` solicita. +As requisições correspondentes então recebem a imagem como `image/webp` ou `image/avif`, o formato que o parâmetro `ims` solicita. ### Cada requisição para a mesma imagem derivada chega a Image Processor diff --git a/apps/docs/src/content/docs/pt-br/pages/build/cache/cache-keys.mdx b/apps/docs/src/content/docs/pt-br/pages/build/cache/cache-keys.mdx index 1b5d155cda..8a19103b1b 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/cache/cache-keys.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/cache/cache-keys.mdx @@ -12,7 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Uma cache key é a entrada de índice sob a qual [Cache](/pt-br/documentacao/plataforma/applications/cache/) armazena um objeto. A Azion a monta a partir da requisição: o scheme, o host, o path e as variações que um cache setting ou [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) acrescenta. Uma requisição cuja key casa com um objeto válido armazenado é respondida com esse objeto. Caso contrário, a origem ou uma [Function](/pt-br/documentacao/plataforma/functions/) constrói a resposta, e a Azion pode armazenar essa resposta sob essa key. Para o processo de busca, consulte [Expiração e atualização](/pt-br/documentacao/plataforma/applications/cache/expiracao-e-atualizacao/). Para os campos que acrescentam variações, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/). +Uma cache key é a entrada de índice sob a qual [Cache](/pt-br/documentacao/plataforma/applications/cache/) armazena um objeto. A Azion a monta a partir da requisição: o scheme, o host, o path e as variações que um cache setting ou [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) acrescenta. Para saber como uma requisição encontra um objeto armazenado e o que acontece quando não encontra, consulte a [visão geral do Cache](/pt-br/documentacao/plataforma/applications/cache/#caminho-da-requisicao). Para os campos que acrescentam variações, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/). --- @@ -28,23 +28,29 @@ A key padrão concatena três elementos da URI da requisição, nesta ordem: A query string não faz parte da key padrão: `https://static.example.com/page/site.js?city=city&name=name` gera a mesma key que a URI sem ela. A variação por query string, em Variações, a acrescenta. -A URI `https://static.example.com/page/site.js` gera a key `httpsstatic.example.com/page/site.js`. As keys diferenciam maiúsculas de minúsculas: caracteres maiúsculos e minúsculos são distintos. Quando um cache setting ativa uma variação, a key pode terminar com o separador `@@`, como em `httpsstatic.example.com/page/site.js@@`. A tabela em Variações mostra onde cada variação entra: o método da requisição é um prefixo, e as outras variações vêm depois de `@@`, inclusive a query string quando o behavior dela é `allowlist` ou `denylist`. Com `all`, a query string inteira vem depois do path, antes de `@@`. +A URI `https://static.example.com/page/site.js` gera a key `httpsstatic.example.com/page/site.js`. As keys diferenciam maiúsculas de minúsculas: caracteres maiúsculos e minúsculos são distintos. + +Quando um cache setting ativa uma variação, a key pode terminar com o separador `@@`, como em `httpsstatic.example.com/page/site.js@@`. A tabela em Variações mostra onde cada variação entra: o método da requisição é um prefixo, e as outras variações vêm depois de `@@`, inclusive a query string quando o behavior dela é `allowlist` ou `denylist`. Com `all`, a query string inteira vem depois do path, antes de `@@`. --- ## Variações -Uma variação altera a key padrão, de modo que uma URI pode manter mais de um objeto no cache. A tabela lista o que cada variação acrescenta e a key que ela gera. +Uma variação é uma entrada da requisição, além do scheme, do host e do path, que varia a cache key. Cada variação acrescenta um marcador à key padrão, de modo que uma URI pode manter uma cópia separada para cada valor dessa entrada. A tabela lista o que cada variação acrescenta e a key que ela gera. | Variação | O que é acrescentado | Exemplo de key | | --- | --- | --- | -| Requisição complexa | O método da requisição, como prefixo da key. Uma requisição `GET` ou `HEAD` não recebe prefixo. | `optionshttpsstatic.example.com/page` | -| Query string | Com `allowlist` e `denylist`: `@@` e, em seguida, `?` e os argumentos que o cache setting mantém. Com `all`: `?` e a query string inteira, depois do path e antes de `@@`. | `httpstatic.example.com/page@@?name=name`, `httpstatic.example.com/page?city=city&name=name@@` | -| Cookies | Com `allowlist` e `denylist`: `@@` e, em seguida, cada nome e valor de cookie que o cache setting mantém, seguidos de `;`. A variação vazia, sem valor de cookie, é `@@;`. Com `all`, o header `Cookie` inteiro vem depois de `@@` como chegou, com os espaços. | `httpwww.example.com/@@;`, `httpwww.example.com/@@user=user;` | -| Device group | `@@` e o nome do device group. | `httpwww.example.com/@@Mobile` | -| [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) | O formato de imagem convertido, no fim da key e sem separador. Quando o cache setting nomeia `ims` na allowlist de query string, a query string `ims` vem depois de `@@`, e o formato vem depois dela. Quando o cache setting não varia a key por query string, o valor de `ims` não faz parte da key, então todos os tamanhos e processamentos do path compartilham uma key, e o primeiro armazenado responde a todos os valores de `ims`. | `httpsstatic.example.com/static/images/image_1.jpg@@webp`, `httpsstatic.example.com/static/images/image_1.jpg@@?ims=880xwebp` | -| Large File Optimization | `@@bytes=-` para cada fragmento, de modo que cada fragmento tem sua própria key. Um arquivo de 2.097.152 bytes gera duas keys. | `httpsstatic.example.com/media/file.mp4@@bytes=0-1048575`, `httpsstatic.example.com/media/file.mp4@@bytes=1048576-2097151` | -| `POST` em cache | `@@` e o hash MD5 (Message Digest 5) do corpo da requisição, depois do prefixo `post`. Um `OPTIONS` em cache carrega apenas o prefixo `options`. | `posthttpsdynamic.example.com/path@@`, `optionshttpsdynamic.example.com/path` | +| Requisição complexa | O método da requisição, como prefixo da key | `optionshttpsstatic.example.com/page` | +| Query string | Com `allowlist` e `denylist`: `@@`, `?` e os argumentos mantidos. Com `all`: `?` e a query string inteira, antes de `@@` | `httpstatic.example.com/page@@?name=name`, `httpstatic.example.com/page?city=city&name=name@@` | +| Cookies | Com `allowlist` e `denylist`: `@@` e cada nome e valor de cookie mantido, cada um seguido de `;` | `httpwww.example.com/@@;`, `httpwww.example.com/@@user=user;` | +| Device group | `@@` e o nome do device group | `httpwww.example.com/@@Mobile` | +| [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) | O formato de imagem convertido, no fim da key e sem separador | `httpsstatic.example.com/static/images/image_1.jpg@@webp`, `httpsstatic.example.com/static/images/image_1.jpg@@?ims=880xwebp` | +| Large File Optimization | `@@bytes=-`, uma key para cada fragmento | `httpsstatic.example.com/media/file.mp4@@bytes=0-1048575`, `httpsstatic.example.com/media/file.mp4@@bytes=1048576-2097151` | +| `POST` em cache | `@@` e o hash MD5 (Message Digest 5) do corpo da requisição, depois do prefixo `post` | `posthttpsdynamic.example.com/path@@`, `optionshttpsdynamic.example.com/path` | + +Uma requisição `GET` ou `HEAD` não recebe prefixo de método, e um `OPTIONS` em cache carrega apenas o prefixo `options`. A variação vazia de cookie, sem valor de cookie, é `@@;`. Com `all`, o header `Cookie` inteiro vem depois de `@@` como chegou, com os espaços. Um arquivo de 2.097.152 bytes gera duas keys de fragmento. + +Quando o cache setting nomeia `ims` na allowlist de query string, a query string `ims` vem depois de `@@`, e o formato da imagem vem depois dela. Quando o cache setting não varia a key por query string, o valor de `ims` não faz parte da key. Todos os tamanhos e processamentos do path então compartilham uma key, e o primeiro armazenado responde a todos os valores de `ims`. Os campos de query string e de cookie diferenciam maiúsculas de minúsculas, então `user` e `User` são duas variações. Com `sort_enabled` ativo no cache setting, `?name=name&city=city` e `?city=city&name=name` compartilham uma key, com os argumentos em ordem alfabética. @@ -72,7 +78,9 @@ x-cache: MISS from 192.0.2.10 with HTTP/2.0 x-cache-key: httpsstatic.example.com/page/site.js ``` -Em HTTP/2, os nomes dos headers chegam em minúsculas. Uma resposta `GET` ou `HEAD` que a Azion não armazena carrega `-` nos dois headers enquanto Application Accelerator está ativo; com ele desativado, a mesma resposta reporta `MISS`, com a sua key em `x-cache-key` e `x-cache-expires-in: 0`. Uma resposta `POST`, `PUT`, `PATCH`, `DELETE` ou `OPTIONS` que a Azion não armazena carrega `-` nos dois casos. Cada uma das requisições seguidas para um path pode ser respondida por um servidor diferente, que o `x-cache` nomeia. Para o procedimento, consulte [Verifique o status de cache de uma resposta](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/verificar-tempo-de-cache-da-pagina/). +Em HTTP/2, os nomes dos headers chegam em minúsculas. Uma resposta `GET` ou `HEAD` que a Azion não armazena carrega `-` nos dois headers enquanto Application Accelerator está ativo. Com Application Accelerator desativado, a mesma resposta reporta `MISS`, com a sua key em `x-cache-key` e `x-cache-expires-in: 0`. + +Uma resposta `POST`, `PUT`, `PATCH`, `DELETE` ou `OPTIONS` que a Azion não armazena carrega `-` nos dois casos. Cada uma das requisições seguidas para um path pode ser respondida por um servidor diferente, que o `x-cache` nomeia. Para o procedimento, consulte [Verifique o status de cache de uma resposta](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/verificar-tempo-de-cache-da-pagina/). --- diff --git a/apps/docs/src/content/docs/pt-br/pages/build/cache/como-funciona.mdx b/apps/docs/src/content/docs/pt-br/pages/build/cache/como-funciona.mdx index 4189b1188f..935c9d9f91 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/cache/como-funciona.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/cache/como-funciona.mdx @@ -9,7 +9,9 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -O tempo durante o qual uma cópia em cache responde no lugar da origem decide duas coisas: quão atualizada é uma resposta e com que frequência a origem é consultada. Em uma Application, [Cache](/pt-br/documentacao/plataforma/applications/cache/) é o recurso da plataforma que armazena a cópia, e um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) define esse tempo como o tempo de vida (TTL) dela. O cache setting também decide o que acontece depois que o TTL termina. Um purge encerra uma cópia antes do prazo. A [visão geral do Cache](/pt-br/documentacao/plataforma/applications/cache/#caminho-da-requisicao) mostra como uma requisição chega a uma cópia em cache, com um diagrama do caminho do cache. +O tempo durante o qual uma cópia em cache responde no lugar da origem decide duas coisas: quão atualizada é uma resposta e com que frequência a origem é consultada. Em uma Application, [Cache](/pt-br/documentacao/plataforma/applications/cache/) é o recurso da plataforma que armazena a cópia. Um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/), um conjunto de valores que dizem ao Cache como armazenar e entregar uma resposta, define esse tempo como o tempo de vida (TTL) da cópia. + +O cache setting também decide o que acontece depois que o TTL termina, e um purge encerra uma cópia antes do prazo. A [visão geral do Cache](/pt-br/documentacao/plataforma/applications/cache/#caminho-da-requisicao) mostra como uma requisição chega a uma cópia em cache, com um diagrama do caminho do cache. As seções cobrem TTL e expiração, stale cache, Large File Optimization, cache keys e variações, Tiered Cache e purge. @@ -17,15 +19,19 @@ As seções cobrem TTL e expiração, stale cache, Large File Optimization, cach ## TTL e expiração -Um cache setting carrega dois TTLs. O TTL de browser controla por quanto tempo o browser de um visitante mantém a sua cópia. O TTL de cache controla por quanto tempo a Azion mantém a dela. Uma requisição que o browser responde pela sua cópia termina no browser, e uma requisição que a Azion responde pela cópia dela termina na Azion. +Um cache setting carrega dois TTLs. O TTL de navegador controla por quanto tempo o navegador de um visitante mantém a sua cópia. O TTL de cache controla por quanto tempo a Azion mantém a dela. Uma requisição que o navegador responde pela sua cópia termina no navegador, e uma requisição que a Azion responde pela cópia dela termina na Azion. + +De onde vem cada TTL depende do comportamento que o setting seleciona para cada cópia. Para a cópia da Azion, o comportamento é o campo `modules.cache.behavior`. _Honor cache policies_ (`honor`) mantém os headers `Cache-Control` e `Expires` da origem e os repassa ao navegador, então a origem decide por quanto tempo o seu conteúdo vive. -De onde vem cada TTL depende do comportamento que o setting seleciona para cada cópia. Para a cópia da Azion, o comportamento é o campo `modules.cache.behavior`. _Honor cache policies_ (`honor`) mantém os headers `Cache-Control` e `Expires` da origem e os repassa ao browser, então a origem decide por quanto tempo o seu conteúdo vive. _Override cache behavior_ (`override`) substitui esses headers, para o cache da Azion, pelo Max Age, o campo `modules.cache.max_age`. Quando a origem não envia TTL sob _Honor cache policies_, a Azion mantém a cópia pelo Max Age do setting. A cópia do browser tem o seu próprio comportamento no campo `browser_cache.behavior`: _Honor cache policies_, _Override cache settings_ ou _No cache_. +_Override cache behavior_ (`override`) substitui esses headers, para o cache da Azion, pelo Max Age, o campo `modules.cache.max_age`. Quando a origem não envia TTL sob _Honor cache policies_, a Azion mantém a cópia pelo Max Age do setting. A cópia do navegador tem o seu próprio comportamento no campo `browser_cache.behavior`: _Honor cache policies_, _Override cache settings_ ou _No cache_. -A cópia expira quando o TTL de cache termina, e a requisição seguinte pelo objeto vai à origem. Quando a origem retorna o objeto, essa resposta atualiza a cópia. A resposta informa `EXPIRED`. Uma verificação com headers condicionais também pode encontrar a cópia inalterada. A resposta então informa `REVALIDATED`, e a origem confirma a cópia em vez de enviar o objeto de novo. +A cópia expira quando o TTL de cache termina, e a requisição seguinte pelo objeto vai à origem. Quando a origem retorna o objeto, essa resposta atualiza a cópia, e a resposta informa `EXPIRED`. Uma verificação com headers condicionais também pode encontrar a cópia inalterada. A resposta então informa `REVALIDATED`, e a origem confirma a cópia em vez de enviar o objeto de novo. Uma requisição que não encontra uma cópia válida é um cache miss. Em um miss, a plataforma limita o trabalho da origem. Quando várias requisições pelo mesmo objeto fora do cache chegam ao mesmo servidor ao mesmo tempo, esse servidor abre uma conexão com a origem para todas elas. Então, sob uma rajada de requisições por um objeto fora do cache, a origem vê uma busca por servidor que recebeu a rajada, não uma por visitante. -O TTL é uma troca entre a carga na origem e a idade do que um visitante vê. Um TTL longo responde mais requisições pela cópia e chega menos à origem, mas o conteúdo que a origem já alterou permanece na cópia até ela expirar. Um TTL curto mantém a cópia próxima da versão da origem, ao preço de mais buscas na origem. Por exemplo, uma Application pode ter dois cache settings, cada um aplicado pela sua própria regra. Imagens que raramente mudam recebem um TTL de um dia, e uma listagem que muda ao longo do dia recebe um TTL de alguns minutos. +O TTL é uma troca entre a carga na origem e a idade do que um visitante vê. Um TTL longo responde mais requisições pela cópia e chega menos à origem, mas o conteúdo que a origem já alterou permanece na cópia até ela expirar. Um TTL curto mantém a cópia próxima da versão da origem, ao preço de mais buscas na origem. + +Por exemplo, uma Application pode ter dois cache settings, cada um aplicado pela sua própria regra. Imagens que raramente mudam recebem um TTL de um dia, e uma listagem que muda ao longo do dia recebe um TTL de alguns minutos. O Max Age tem um piso e um teto, e [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) reduz o piso. Para cada limite de TTL, consulte [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#cache-settings). Para saber como um TTL de 0 segundos difere de contornar o cache, consulte [Bypass Cache e um TTL de 0](/pt-br/documentacao/plataforma/applications/application-accelerator/variacao-de-cache/#bypass-cache-e-um-ttl-de-0). @@ -39,9 +45,7 @@ Uma cópia além do seu TTL ainda tem utilidade. Com o stale cache ativo no cach - A conexão excede o tempo limite, ou a origem está inacessível. - Os headers de cache-control da origem são inválidos ou estão ausentes. -O tempo durante o qual a cópia expirada pode ser entregue é a janela de stale. Sob _Honor cache policies_, a janela é o valor da diretiva `stale-while-revalidate=` que a origem fornece. Sob _Override cache behavior_, ou quando a origem omite a diretiva, a janela é de 300 segundos. - -Uma resposta entregue a partir de uma cópia expirada porque a origem não respondeu informa `STALE`. +O tempo durante o qual a cópia expirada pode ser entregue é a janela de stale. Sob _Honor cache policies_, a janela é o valor da diretiva `stale-while-revalidate=` que a origem fornece. Sob _Override cache behavior_, ou quando a origem omite a diretiva, a janela é de 300 segundos. Uma resposta entregue a partir de uma cópia expirada porque a origem não respondeu informa `STALE`. Stale cache mostra aos visitantes uma página antiga em vez de uma página de erro durante uma indisponibilidade da origem, pelo tempo que a janela durar. O custo é a atualidade: um visitante dentro da janela pode receber conteúdo que a origem já substituiu. Então uma alteração que cada visitante precisa ver de imediato é um caso para um purge, e não para a expiração. @@ -51,7 +55,9 @@ Se o stale cache começa ativo em um setting novo depende da interface. O campo ## Large File Optimization -Um objeto grande pode ser armazenado em cache em fragmentos, e não como uma peça única. Com a Large File Optimization ativa no cache setting, no campo `modules.cache.large_file_cache.enabled` dele, a Azion divide o arquivo em fragmentos de 1.024 kB. Cada fragmento é entregue conforme o usuário o consome e é armazenado em cache sob demanda, no momento em que é requisitado. A cache key de um fragmento termina em `@@bytes=` e no byte range do fragmento. Então cada fragmento é um objeto próprio. +Um objeto grande pode ser armazenado em cache em fragmentos, e não como uma peça única. Com a Large File Optimization ativa no cache setting, no campo `modules.cache.large_file_cache.enabled` dele, a Azion divide o arquivo em fragmentos de 1.024 kB. Cada fragmento é entregue conforme o usuário o consome e é armazenado em cache sob demanda, no momento em que é requisitado. + +Cada fragmento recebe a sua própria cache key, a entrada de índice sob a qual o Cache armazena uma cópia. A key de um fragmento termina em `@@bytes=` e no byte range do fragmento, então cada fragmento é um objeto próprio. Por exemplo, um vídeo de 2.097.151 bytes em `https://static.example.com/media/file.mp4` gera dois fragmentos. Eles são armazenados sob estas keys: @@ -68,7 +74,9 @@ O custo aparece na hora do purge. Um arquivo se torna muitas keys, então um pur ## Cache keys e variações -Uma variação é uma cópia adicional de um path, armazenada sob a sua própria cache key porque algo além do path é diferente. Enquanto nenhuma variação está ativa, um path é um objeto armazenado. A Azion monta a key padrão a partir do scheme, do host e do path da requisição. Um cache setting guarda a sua variação por query string no campo `cache_vary_by_querystring.behavior`, que começa em `ignore` e mantém a query string fora da key. Quando algo além do path altera a resposta, o cache setting o nomeia, e a key carrega um marcador para ele. +Uma variação é uma entrada da requisição, além do scheme, do host e do path, que varia a cache key. O Cache mantém uma cópia separada para cada valor de uma variação, sob a sua própria cache key. Enquanto nenhuma variação está ativa, um path é um objeto armazenado, e a Azion monta a key padrão a partir do scheme, do host e do path da requisição. + +Um cache setting guarda a sua variação por query string no campo `cache_vary_by_querystring.behavior`, que começa em `ignore` e mantém a query string fora da key. Quando algo além do path altera a resposta, o cache setting o nomeia, e a key carrega um marcador para ele. Quatro entradas podem variar uma cópia pelo objeto `modules.application_accelerator` de um cache setting: @@ -77,25 +85,52 @@ Quatro entradas podem variar uma cópia pelo objeto `modules.application_acceler - O device group em que a requisição se encaixa. - O método da requisição. -Outras duas vêm de outros lugares. [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) acrescenta o formato da imagem quando converte uma imagem, e Large File Optimization acrescenta o byte range de cada fragmento. Cada valor distinto é uma key separada, então cada um é armazenado e purgado separadamente. +Outras duas vêm de outros lugares. [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) acrescenta o formato da imagem quando converte uma imagem, e Large File Optimization acrescenta o byte range de cada fragmento. Os device groups pertencem à Application, e [Device Groups](/pt-br/documentacao/plataforma/applications/device-groups/) os documenta. Com `cache_vary_by_devices`, um setting entrega uma única versão independentemente do dispositivo, ou mantém uma cópia por grupo nomeado. O método também é uma variação. Respostas `GET` e `HEAD` são armazenadas em cache nativamente, e respostas `POST` e `OPTIONS` só são armazenadas em cache com Application Accelerator ativo e o método listado em `cache_vary_by_method`. O corpo de um `POST` então passa a fazer parte da key como um hash MD5, então dois corpos diferentes enviados a um path são dois objetos. A key de um `OPTIONS` carrega apenas o prefixo do método. -Uma variação divide as requisições por um path entre várias cópias. Menos requisições encontram uma cópia já presente, e um purge precisa alcançar cada cópia. Por exemplo, uma página de listagem que varia por um argumento `page` armazena uma cópia por número de página, e um purge da listagem precisa nomear cada uma delas. Para o marcador que cada variação acrescenta, consulte [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#variacoes). Para os campos que ativam uma variação, consulte [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#cache-variation). +Uma variação divide as requisições por um path entre várias cópias. Menos requisições encontram uma cópia já presente, e um purge precisa alcançar cada cópia. Por exemplo, uma página de listagem que varia por um argumento `page` armazena uma cópia por número de página, e um purge da listagem precisa nomear cada uma delas. + +Para o marcador que cada variação acrescenta, consulte [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#variacoes). Para os campos que ativam uma variação, consulte [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#cache-variation). --- ## Tiered Cache -[Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) é uma feature de Cache que adiciona uma segunda camada de cache entre o data center que responde a uma requisição e a origem. Quando esse data center não tem uma cópia válida, ele consulta a camada do Tiered Cache antes que a requisição siga para a origem. Uma cópia válida nessa camada responde ao miss, e a origem não recebe nenhuma requisição. +[Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) é uma feature de Cache que adiciona uma segunda camada de cache entre o data center que responde e a origem. + +As setas sólidas levam a requisição, e as setas pontilhadas levam a resposta. Cada rótulo começa com o número do seu passo abaixo. + +```mermaid +%%{init: {"layout": "elk", "elk": {"cycleBreakingStrategy": "MODEL_ORDER"}, "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% +flowchart TD + Client(["Cliente"]) + DC["data center: primeira camada"] + Tier["camada do Tiered Cache"] + Origin[["servidor de origem"]] + Client -->|"1. requisição"| DC + DC -->|"2. sem cópia válida"| Tier + Tier -.->|"3. cópia válida"| DC + Tier -->|"4. sem cópia válida"| Origin + Origin -.->|"4. resposta"| Tier + Tier -.->|"4. resposta"| DC + DC -.->|"1, 3, 4. resposta"| Client +``` + +1. A requisição chega ao data center que a responde, que responde pelo seu próprio cache quando tem uma cópia válida. +2. Quando esse data center não tem uma cópia válida, ele consulta a camada do Tiered Cache. +3. Uma cópia válida na camada do Tiered Cache responde ao miss, e a origem não recebe nenhuma requisição. +4. Caso contrário, a requisição vai à origem, e a resposta volta ao data center pela camada do Tiered Cache. Cada cache setting ativa a camada no seu campo `modules.cache.tiered_cache.enabled`, e todos os planos a incluem. O setting nomeia uma topologia em `modules.cache.tiered_cache.topology`: a região que mantém a camada, como `nearest-region` ou `us-east-1`. Tiered Cache também exige _Override cache behavior_. Sob _Honor cache policies_, a API recusa o setting com `21001`. -A troca é um salto extra e um piso no TTL. Um miss na primeira camada vai até a segunda antes de chegar à origem. Um setting com Tiered Cache ativo também carrega um TTL mínimo. Em troca, menos requisições chegam à origem. Para o mínimo, consulte [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#cache-settings). +A troca é um salto extra e um piso no TTL. Um miss na primeira camada vai até a segunda antes de chegar à origem. Em troca, uma resposta da camada do Tiered Cache chega com menos latência do que uma resposta da origem, e menos requisições chegam à origem, então a origem lida com menos carga a um custo de infraestrutura menor. Para o TTL mínimo, consulte [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#cache-settings). -Uma regra com _Bypass Cache_ afeta o cache da Azion, e não a camada do Tiered Cache. Uma Application com cache settings de Tiered Cache ativos continua a armazenar objetos em cache nessa camada pelo Max Age do cache setting. A camada é purgada por cache key. Quando você purga um objeto mantido nas duas camadas, purgue primeiro a camada do Tiered Cache e depois a camada do Cache. Caso contrário, a primeira camada é reabastecida com conteúdo desatualizado do Tiered Cache. Para as camadas de purge, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#camadas). +Uma regra com _Bypass Cache_ afeta o cache da Azion, e não a camada do Tiered Cache. Uma Application com cache settings de Tiered Cache ativos continua a armazenar objetos em cache nessa camada pelo Max Age do cache setting. + +A camada do Tiered Cache é purgada por cache key, e a ordem dos purges decide o que a primeira camada mantém. Quando o Cache é purgado antes da camada do Tiered Cache, a primeira camada é reabastecida com conteúdo desatualizado do Tiered Cache. Então um objeto mantido nas duas camadas sai primeiro da camada do Tiered Cache e depois do Cache. Para as camadas de purge, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#camadas). --- @@ -103,9 +138,15 @@ Uma regra com _Bypass Cache_ afeta o cache da Azion, e não a camada do Tiered C Um purge remove uma cópia armazenada antes do fim do seu TTL. Quando nenhuma camada tem uma cópia, a requisição seguinte pelo objeto vai à origem, a resposta informa `MISS` e a versão que a origem retorna é armazenada. Um purge entra em fila depois que você o confirma, porque o resultado leva tempo para se propagar. Ele aparece no histórico de purges quando termina em toda a infraestrutura da Azion. -Um purge encontra um objeto pela sua cache key, então o tipo de purge importa para um objeto que varia. Um purge por URL converte cada URL em uma cache key sem considerar a variação de conteúdo. Então uma cópia que varia por cookie, device group ou formato de imagem sobrevive a ele. Um purge por cache key nomeia cada variação. Um purge por wildcard alcança cada key que corresponde a uma expressão com `*`. As variações por query string são a exceção que um purge por URL alcança. Os argumentos precisam ser enviados na ordem em que foram apresentados, ou em ordem alfabética quando o cache setting os ordena, no campo `cache_vary_by_querystring.sort_enabled` dele. +Um purge encontra um objeto pela sua cache key, então o tipo de purge importa para um objeto que varia. Cada um dos três tipos de purge alcança um conjunto diferente de keys: + +- Um purge por URL converte cada URL em uma cache key sem considerar a variação de conteúdo, então uma cópia que varia por cookie, device group ou formato de imagem sobrevive a ele. +- Um purge por cache key nomeia a key de cada cópia. +- Um purge por wildcard alcança cada key que corresponde a uma expressão com `*`. + +As variações por query string são a exceção que um purge por URL alcança. Os argumentos precisam ser enviados na ordem em que foram apresentados, ou em ordem alfabética quando o cache setting os ordena, no campo `cache_vary_by_querystring.sort_enabled` dele. -Um purge é a ferramenta para uma alteração que não pode esperar o TTL. O seu custo é a busca na origem que reabastece cada key purgada. Quanto mais keys um objeto tem, por variações ou por fragmentos, mais um purge precisa nomear. Para os tipos de purge e os seus argumentos, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/). Para os passos, consulte [Purgue conteúdo em cache](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/purgar-conteudo-em-cache/). +Um purge é a ferramenta para uma alteração que não pode esperar o TTL. O seu custo é a busca na origem que reabastece cada key purgada, uma por fragmento ou por cópia de uma variação. Para os tipos de purge e os seus argumentos, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/). Para os passos, consulte [Purgue conteúdo em cache](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/purgar-conteudo-em-cache/). --- diff --git a/apps/docs/src/content/docs/pt-br/pages/build/cache/primeiros-passos.mdx b/apps/docs/src/content/docs/pt-br/pages/build/cache/primeiros-passos.mdx index 4b2f5d8c4f..8753b0db3a 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/cache/primeiros-passos.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/cache/primeiros-passos.mdx @@ -21,7 +21,7 @@ Este guia orienta você a colocar em cache um path da sua Application pela prime - Uma regra do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) que aplica o setting a um prefixo de path. - O status de cache de uma resposta, lido no seu header `x-cache`. -O resultado se apoia em quatro objetos, nesta ordem. A **Application** tem [Cache](/pt-br/documentacao/plataforma/applications/cache/) ativo, como toda Application. O **cache setting** pertence à Application. Ele carrega o tempo de vida (TTL), por quanto tempo a Azion mantém uma cópia. Ele também carrega o que a Azion faz com essa cópia. +O resultado se apoia em uma Application, um cache setting, uma regra e uma requisição, nesta ordem. A **Application** tem [Cache](/pt-br/documentacao/plataforma/applications/cache/) ativo, como toda Application. O **cache setting** pertence à Application. Ele é um conjunto de valores que dizem ao Cache como armazenar e entregar uma resposta, como o tempo de vida (TTL), por quanto tempo a Azion mantém uma cópia. A **regra**, também na Application, corresponde a requisições por path e aplica o setting pelo behavior _Set Cache Policy_. Um cache setting só age depois que uma regra aplica esse cache setting. Uma **requisição** correspondente é respondida pela cópia armazenada quando existe uma. Com o header `Pragma: azion-debug-cache`, a sua resposta informa `HIT` no `x-cache`. @@ -73,7 +73,7 @@ A **regra**, também na Application, corresponde a requisições por path e apli ## Crie um cache setting -Um cache setting carrega por quanto tempo a Azion mantém uma cópia de uma resposta e o que a Azion faz com essa cópia. Este mantém cada cópia por 300 segundos. +Um cache setting é um conjunto de valores que dizem ao Cache como armazenar e entregar uma resposta. Este mantém cada cópia por 300 segundos. @@ -86,7 +86,7 @@ Para criar o cache setting pelo Azion Console: - Acesse [Azion Console](https://console.azion.com/) > **Applications** e selecione a Application que entrega o seu conteúdo. + Acesse [Azion Console](https://console.azion.com/) > **Applications** > sua Application. @@ -150,9 +150,9 @@ Para criar o cache setting com a Azion CLI, substitua `` pelo ID - Substitua `123460` pelo ID que o comando de criação retornou: + Substitua `` pelo ID que o comando de criação retornou: - --cache-setting-id 123460 --format json`} /> + --cache-setting-id --format json`} /> A saída reporta o `modules.cache.max_age` como `300`. @@ -162,7 +162,7 @@ Para criar o cache setting com a Azion CLI, substitua `` pelo ID O cache setting existe na Application. Registre o seu ID: a regra da próxima etapa aplica o setting por esse ID. :::note[nota] -Só o corpo da requisição, passado com `--file`, define o `max_age`, o comportamento de cache, o stale cache e a Large File Optimization. A flag `--tiered-caching-enabled` falha sem o behavior `override`, e só o corpo define esse behavior. Para todas as flags que o comando aceita, consulte [Azion CLI cache-setting](/pt-br/documentacao/devtools/cli/recursos/cache-setting/#criar). +Só o corpo da requisição, passado com `--file`, define o `max_age`, o comportamento de cache, o stale cache e a Large File Optimization. A flag `--tiered-caching-enabled` falha sem o comportamento `override`, e só o corpo define esse comportamento. Para todas as flags que o comando aceita, consulte [Azion CLI cache-setting](/pt-br/documentacao/devtools/cli/recursos/cache-setting/#criar). ::: @@ -250,7 +250,7 @@ Para criar a regra pelo Azion Console: - Acesse [Azion Console](https://console.azion.com/) > **Applications** e selecione a Application que entrega o seu conteúdo. + Acesse [Azion Console](https://console.azion.com/) > **Applications** > sua Application. @@ -409,7 +409,7 @@ Uma regra nova pode levar alguns minutos para propagar. Aguarde antes de verific ## Verifique o status de cache -O header de requisição `Pragma: azion-debug-cache` faz a resposta carregar dois headers de debug. O `x-cache` carrega o status de cache, o IP do servidor que respondeu e o protocolo. O `x-cache-key` carrega a key que indexa a cópia. +Para ler o status de cache, requisite um objeto com o header `Pragma: azion-debug-cache`: a resposta carrega dois headers de debug. O header `x-cache` carrega o status de cache, o IP do servidor que respondeu e o protocolo. O header `x-cache-key` carrega a key que indexa a cópia. @@ -434,7 +434,12 @@ O header de requisição `Pragma: azion-debug-cache` faz a resposta carregar doi - Uma resposta entregue pela cópia armazenada carrega `HIT`. O `x-cache` também nomeia o servidor que respondeu. Cada servidor guarda a sua própria cópia, então uma requisição que outro servidor responde pode informar `MISS` mais uma vez. Execute o comando novamente. + Uma resposta entregue pela cópia armazenada carrega `HIT`. O `x-cache` também nomeia o servidor que respondeu. Cada servidor guarda a sua própria cópia, então uma requisição que outro servidor responde pode informar `MISS` mais uma vez. + + + + + Se a resposta informar `MISS`, execute o comando novamente. diff --git a/apps/docs/src/content/docs/pt-br/pages/build/cache/visao-geral.mdx b/apps/docs/src/content/docs/pt-br/pages/build/cache/visao-geral.mdx index 106f758300..cca8fb7f6a 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/cache/visao-geral.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/cache/visao-geral.mdx @@ -10,20 +10,21 @@ import DocButton from '~/components/webkit/DocButton.vue' import DocCardGroup from '@aziontech/webkit/doc-card-group' import DocCard from '@aziontech/webkit/doc-card' -**Cache** é um recurso da plataforma que armazena cópias das respostas às requisições recebidas pelas suas [Applications](/pt-br/documentacao/plataforma/applications/), na infraestrutura distribuída da Azion. Um cache é um armazenamento de cópias de respostas entre os clientes e a origem, o servidor que guarda o conteúdo. Ele responde às requisições repetidas com essas cópias. +**Cache** é um recurso da plataforma que armazena cópias das respostas às requisições recebidas pelas suas [Applications](/pt-br/documentacao/plataforma/applications/), do data center mais próximo ao seu usuário. Um cache é um armazenamento de cópias de respostas, entre os clientes e a origem, que responde às requisições repetidas sem consultar a origem. Cache também pode remover cópias armazenadas sob demanda com [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/). Use Cache para entregar arquivos estáticos, vídeos grandes em fragmentos e cópias expiradas se a origem falhar. -A primeira requisição por um objeto chega à origem, e o cache armazena a resposta sob uma key montada a partir da requisição. As requisições seguintes com a mesma key recebem a cópia armazenada. A cópia dura até que o seu tempo de vida (TTL), um período em segundos, termine. Assim, a origem responde apenas à primeira requisição e às que chegam depois que a cópia expira. +Em cada Application, Cache pode usar estes recursos aninhados e features: -Cache está sempre ativo em uma Application. Ele armazena apenas as respostas às requisições que correspondem a uma regra do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) com o behavior _Set Cache Policy_. Essa regra aplica um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/), que guarda os TTLs e decide como a Azion armazena e varia cada cópia. Cache pode armazenar uma resposta construída pela origem ou por uma [Function](/pt-br/documentacao/plataforma/functions/). Cada cópia fica no data center que a armazenou. Use Cache para manter arquivos estáticos no data center mais próximo ao seu usuário, entregar vídeos grandes em fragmentos com a Large File Optimization, responder com uma cópia expirada por meio do stale cache enquanto a origem está fora do ar ou remover uma cópia com [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/) quando a origem muda. +- [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/) permite entregar uma atualização que a origem já tem antes do fim do tempo de vida (TTL) de uma cópia. Use-o para remover um objeto obsoleto ou para controlar o que a Azion entrega em conteúdo dinâmico. +- [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) permite que uma Application responda a um cache miss a partir de uma segunda camada de cache antes que a requisição chegue à origem. A origem então recebe menos requisições e lida com menos carga. - + --- ## Caminho da requisição -Criar um cache setting não armazena nada em cache: uma requisição só chega a uma cópia armazenada por meio de uma regra que aplica o setting. +Criar um cache setting não armazena nada: uma requisição só chega a uma cópia armazenada por meio de uma regra que aplica o setting. Um cache setting é um conjunto de valores que dizem ao Cache como armazenar e entregar uma resposta, como os seus TTLs. O próprio Cache está ativo em toda Application, então essa regra é o único passo de que uma cópia precisa. As setas sólidas levam a requisição, e as setas pontilhadas levam a resposta. Cada rótulo começa com o número do seu passo abaixo. @@ -49,58 +50,11 @@ flowchart TD 1. A requisição do cliente chega a uma Application, e as regras da Request Phase da Application são executadas em ordem. 2. Quando uma regra com _Set Cache Policy_ aplica um cache setting, Cache monta a cache key a partir da requisição e de cada variação que o setting nomeia. -3. Quando Cache tem uma cópia válida sob essa key, o data center que recebeu a requisição responde a partir dela. A resposta informa `HIT`. +3. Quando Cache tem uma cópia válida sob essa key, o data center que recebeu a requisição responde a partir dela, porque cada cópia fica no data center que a armazenou. A resposta informa `HIT`. 4. Caso contrário, o Connector definido por uma regra com _Set Connector_ encaminha a requisição à origem, e a resposta informa `MISS`. Cache pode armazenar a resposta sob a key para as requisições seguintes. -5. Quando nenhuma regra aplica um cache setting, ou uma regra com _Bypass Cache_ corresponde à requisição, a requisição vai à origem sem passar por Cache. _Bypass Cache_ exige [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/). Com _Bypass Cache_, nada é armazenado, e a resposta informa `-` ou `BYPASS` em `x-cache`. +5. Quando nenhuma regra aplica um cache setting, ou uma regra com _Bypass Cache_ corresponde à requisição, a requisição vai à origem sem passar por Cache. _Bypass Cache_ exige [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/). Com _Bypass Cache_, o cache da Azion não armazena nenhuma cópia, e a resposta informa `-` ou `BYPASS` em `x-cache`. -Uma cópia armazenada responde até que o seu TTL termine ou um purge a remova. O status volta no header `x-cache` da resposta a uma requisição enviada com `Pragma: azion-debug-cache`. Para cada status e os headers de debug, consulte [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#status-de-cache). - -Para TTL e expiração, stale cache, Large File Optimization, cache keys e variações, Tiered Cache e purge, consulte [Expiração e atualização](/pt-br/documentacao/plataforma/applications/cache/expiracao-e-atualizacao/). - ---- - -## Estrutura do cache setting - -Cache age por meio de um cache setting. O setting guarda por quanto tempo a Azion e o browser mantêm uma cópia, o que a Azion faz com uma cópia expirada e o que torna duas requisições diferentes. Para manter cada resposta por 300 segundos no cache da Azion e por um dia no browser, envie este cache setting como corpo de `POST /v4/workspace/applications//cache_settings`: - -```json -{ - "name": "static-assets", - "browser_cache": { "behavior": "override", "max_age": 86400 }, - "modules": { - "cache": { - "behavior": "override", - "max_age": 300, - "stale_cache": { "enabled": true }, - "large_file_cache": { "enabled": true, "offset": 1024 }, - "tiered_cache": { "enabled": true, "topology": "nearest-region" } - } - } -} -``` - -- `browser_cache` decide o que o browser de um visitante mantém. `honor` repassa os headers `Cache-Control` e `Expires` da origem. `override` os substitui por `max_age`, em segundos. `no-cache` desativa o cache no browser. -- `modules.cache` decide o que a Azion mantém. Com `behavior` definido como `override`, `max_age` substitui os headers da origem. Em `honor`, a Azion mantém esses headers. Quando a origem não envia TTL, a Azion guarda a resposta pelo `max_age` do setting. -- `stale_cache`, `large_file_cache` e `tiered_cache` ativam o stale cache, fragmentos de 1.024 kB e uma segunda camada de cache na região que `topology` nomeia. O stale cache pode entregar uma cópia expirada quando a Azion não consegue confirmar a cópia com a origem. Um corpo que deixa um desses três campos de fora recebe esse campo desativado. O `tiered_cache` também exige o behavior `override`. -- Um cache setting só age depois que uma regra da Request Phase aplica esse cache setting com `{ "type": "set_cache_policy", "attributes": { "value": } }`. Você também pode montar o mesmo setting no Azion Console, como mostra [Primeiros passos com Cache](/pt-br/documentacao/plataforma/applications/cache/primeiros-passos/). - -Se você define headers `Cache-Control` na sua origem, o modelo se mantém: `honor` os preserva e `override` os substitui. - ---- - -## Escopo e limites - -- **Application**: Cache fica sempre ativo em uma Application, no campo `modules.cache.enabled` dela na API, que recusa `false` com `31001`. [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#recursos-da-plataforma) mostra o switch dele travado como ativo no Azion Console, com a nota `Automatically enabled in all accounts.` Uma Application nova não tem cache settings nem regras, então Cache começa a armazenar cópias quando uma regra com _Set Cache Policy_ aplica um cache setting. -- **Cópias expiradas**: com o stale cache ativo, no campo `modules.cache.stale_cache.enabled` de um cache setting, a Azion pode servir uma cópia expirada quando não consegue confirmar a cópia com a origem. A resposta então informa `STALE`. Um setting criado pela [Azion API](https://api.azion.com/) ou pela [Azion CLI](/pt-br/documentacao/devtools/cli/) vem com ele desativado, enquanto Azion Console o ativa em um setting novo. [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#cache) mostra onde alterá-lo em cada interface. Para saber quando uma página antiga é melhor que um erro, consulte [Boas práticas de Applications](/pt-br/documentacao/plataforma/applications/boas-praticas/#cache). -- **Arquivos grandes**: a Large File Optimization, o campo `modules.cache.large_file_cache.enabled` de um cache setting, armazena em cache um objeto grande em fragmentos de 1.024 kB. Ela vem desativada em um cache setting novo. Cada fragmento é buscado quando um usuário chega a ele e armazenado sob uma key própria, então um purge do arquivo precisa nomear cada fragmento ou usar um wildcard. -- **Tiered Cache**: [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) é uma feature de Cache que adiciona uma segunda camada de cache entre o data center que responde a uma requisição e a origem. Cada cache setting ativa essa feature no seu campo `modules.cache.tiered_cache.enabled`, e todos os planos a incluem. Um data center que não tem uma cópia válida consulta essa camada antes que a requisição siga para a origem. Tiered Cache exige o behavior `override` e um TTL mínimo. Uma regra com _Bypass Cache_ age apenas sobre o cache da Azion, então a camada do Tiered Cache continua a armazenar objetos pelo Max Age do cache setting. -- **Keys e variação**: a Azion monta a [cache key](/pt-br/documentacao/plataforma/applications/cache/cache-keys/) padrão a partir do scheme, do host e do path, então um path é um objeto armazenado, e a query string fica fora da key. Variar uma cópia por query string, cookie, device group ou método exige [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/). [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) acrescenta à key o formato de uma imagem convertida. -- **Purge**: [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/) é um recurso da plataforma que remove uma cópia armazenada antes do fim do seu TTL, por URL, por cache key ou por wildcard. A Azion coloca um purge em fila depois que você o confirma, porque o resultado leva tempo para se propagar. O purge aparece no histórico de purges quando termina. Uma cópia que varia por cookie, device group ou formato de imagem sobrevive a um purge por URL, e um purge por cache key ou por wildcard a alcança. -- **Código**: o código que lê e grava entradas em cache é executado em uma [Function](/pt-br/documentacao/plataforma/functions/) e chama [Cache API](/pt-br/documentacao/devtools/runtime/api-reference/cache/), porque o próprio Cache não pode executar código. -- **Interfaces**: você cria cache settings na aba **Cache Settings** de uma Application no Azion Console, pela Azion API em `/v4/workspace/applications//cache_settings` e com comandos da Azion CLI como `azion create cache-setting`. [`azion.config.js`](/pt-br/documentacao/devtools/cli/azion-config-js/) declara um setting como uma entrada do seu array `cache`, [Azion Lib](/pt-br/documentacao/devtools/azion-lib/application/) cria um com `createCacheSetting` e [Azion Terraform Provider](/pt-br/documentacao/devtools/terraform/applications/) gerencia um com o recurso `azion_application_cache_setting`. Um purge é enviado de **Real-Time Purge** no Azion Console, para `POST /v4/workspace/purge/` ou com `azion purge`. -- **Observabilidade**: uma requisição enviada com `Pragma: azion-debug-cache` recebe dois headers. O `x-cache` carrega o status de cache, e o `x-cache-key` carrega a key da cópia. [Real-Time Metrics](/pt-br/documentacao/plataforma/real-time-metrics/) mostra o tráfego de Cache e de Tiered Cache, e [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/) traz um dataset de Tiered Cache. -- **Limites**: um único objeto em cache pode chegar a 10 GB. O Max Age, o campo `modules.cache.max_age` de um cache setting, aceita de 60 segundos a um ano. Com Application Accelerator ativo, a Azion API aceita a partir de 0 segundos. Para cada limite de um cache setting, de um objeto e de um purge, consulte [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#cache). Para os valores, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#cache) e, para o que cada plano inclui, [Preços da Azion](https://www.azion.com/pt-br/precos/). -- **Termos**: o [glossário de Applications](/pt-br/documentacao/plataforma/applications/glossario/) define as palavras às quais as páginas de Cache dão um significado específico, como cache setting, cache key, status de cache e stale cache. +Uma cópia armazenada responde até que o seu TTL, um período em segundos, termine. Cache armazena uma resposta construída pela origem ou por uma [Function](/pt-br/documentacao/plataforma/functions/). O status volta no header `x-cache` da resposta a uma requisição enviada com `Pragma: azion-debug-cache`. Para cada status e os headers de debug, consulte [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#status-de-cache). --- @@ -108,9 +62,11 @@ Se você define headers `Cache-Control` na sua origem, o modelo se mantém: `hon - + + - + + diff --git a/apps/docs/src/content/docs/pt-br/pages/build/image-processor/como-funciona.mdx b/apps/docs/src/content/docs/pt-br/pages/build/image-processor/como-funciona.mdx index e7de6fca0a..4aebc83748 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/image-processor/como-funciona.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/image-processor/como-funciona.mdx @@ -9,7 +9,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Uma imagem construída sob demanda ainda precisa chegar ao navegador em um formato que ele lê, e ser construída uma vez, e não para cada leitor. Em uma [Application](/pt-br/documentacao/plataforma/applications/), [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) é o recurso da plataforma que constrói essa imagem, a imagem derivada, a partir da imagem de origem que está no servidor de origem. Como uma requisição se torna uma imagem derivada, com o diagrama dessa cadeia, está na [visão geral do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/#caminho-da-requisicao). +Uma imagem construída sob demanda ainda precisa chegar ao navegador em um formato que ele lê, e ser construída uma vez, e não para cada leitor. Em uma [Application](/pt-br/documentacao/plataforma/applications/), [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) é o recurso da plataforma que constrói essa imagem, a imagem derivada. Ele a constrói a partir do arquivo no servidor de origem, a imagem de origem. Como uma requisição se torna uma imagem derivada, com o diagrama dessa cadeia, está na [visão geral do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/#caminho-da-requisicao). As seções cobrem como o formato entregue é escolhido, como o cache diferencia uma imagem derivada de outra e onde Image Processor para. @@ -19,9 +19,11 @@ As seções cobrem como o formato entregue é escolhido, como o cache diferencia O formato entregue pode ser diferente do formato da imagem de origem. Dois mecanismos o alteram, e eles se comportam de forma diferente. -O primeiro é explícito. Um filtro `filters:format()` na string `ims` pede um formato de saída nomeado, e a resposta carrega esse formato qualquer que seja o header `Accept` que a requisição enviou, ou sem nenhum. +O primeiro é explícito. Um filtro `filters:format()` no parâmetro de query string `ims` pede um formato de saída nomeado, e a resposta carrega esse formato qualquer que seja o header `Accept` que a requisição enviou, ou sem nenhum. -O segundo é automático e não precisa de nenhum parâmetro `ims`. Image Processor detecta quais formatos o navegador aceita e, quando possível, converte a imagem para um deles, como WEBP ou AVIF. Uma imagem BMP é convertida para JPEG ou WEBP dependendo do mesmo suporte. Por exemplo, uma requisição cujo header `Accept` lista `image/webp`, sem query string, pode receber `image/webp` para uma imagem de origem armazenada como PNG. Uma resposta pode carregar um formato diferente do que está na origem mesmo quando a URL não tem filtro. +O segundo é automático e não precisa de nenhum parâmetro `ims`. Image Processor detecta quais formatos o navegador aceita e, quando possível, converte a imagem para um deles, como WEBP ou AVIF. Uma imagem BMP é convertida para JPEG ou WEBP dependendo do mesmo suporte. + +Por exemplo, uma requisição cujo header `Accept` lista `image/webp`, sem query string, pode receber `image/webp` para uma imagem de origem armazenada como PNG. Então, os bytes na origem e os bytes transmitidos são duas medidas diferentes, e a resposta informa isso. Uma resposta processada carrega `x-ims: Enabled`, e `x-original-image-size` carrega o tamanho da imagem de origem antes da transformação. Leia esses headers antes de comparar uma resposta com o arquivo na origem. Para os headers, consulte [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/#headers-de-resposta). @@ -29,7 +31,9 @@ Então, os bytes na origem e os bytes transmitidos são duas medidas diferentes, ## Uma entrada de cache por transformação -Uma imagem derivada só vale a pena ser construída uma vez. A prática para o cache setting que serve imagens é variar o cache por `ims`: o seu campo `cache_vary_by_querystring` recebe o behavior `allowlist`, com `ims` em `fields`. Cada string `ims` distinta tem então uma cache key própria. Esse campo fica em `modules.application_accelerator` no cache setting, então variar o cache por `ims` exige [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/), enquanto processar uma imagem não exige. [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/#variacao-de-cache) relaciona cada um desses campos ao seu controle no Azion Console. +Uma imagem derivada só vale a pena ser construída uma vez. A prática para o cache setting que serve imagens é variar o cache por `ims`: o seu campo `cache_vary_by_querystring` recebe o behavior `allowlist`, com `ims` em `fields`. Cada valor distinto de `ims` tem então uma cache key própria. + +Esse campo fica em `modules.application_accelerator` no cache setting, então variar o cache por `ims` exige [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/), enquanto processar uma imagem não exige. [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/#variacao-de-cache) relaciona cada um desses campos ao seu controle no Azion Console. Um cache setting criado com essa allowlist é lido de volta com este objeto `modules`: @@ -59,17 +63,17 @@ Um cache setting criado com essa allowlist é lido de volta com este objeto `mod A cache key de uma imagem derivada convertida para outro formato também carrega o formato no fim da key, sem separador, como em `httpsstatic.example.com/static/images/image_1.jpg@@?ims=880xwebp`. -Essa key tem um custo, e o custo é a cardinalidade. Cada string `ims` distinta, em cada formato entregue, é um objeto armazenado distinto. Uma página que pede larguras arbitrárias armazena um objeto por largura e formato, enquanto uma página que pede quatro larguras fixas armazena quatro por formato. Então, escolher um conjunto pequeno de tamanhos é tanto uma decisão de cache quanto uma decisão de layout. +Essa key tem um custo, e o custo é a cardinalidade. Cada valor distinto de `ims`, em cada formato entregue, é uma cópia separada no cache. Uma página que pede larguras arbitrárias armazena uma cópia por largura e formato, enquanto uma página que pede quatro larguras fixas armazena quatro por formato. Então, escolher um conjunto pequeno de tamanhos é tanto uma decisão de cache quanto uma decisão de layout. -Também é uma decisão de cobrança, porque o medidor mensal de Images conta as imagens que Image Processor processa, e não as imagens que o cache serve. Então, uma imagem derivada que permanece em cache é contada quando Image Processor a constrói, e não cada vez que um leitor a recebe. O cache pode remover um objeto pouco acessado antes do fim da idade máxima dele, e a próxima requisição por essa imagem é processada e contada de novo. Para a tarifa, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#image-processor). +O cache também decide quantas vezes uma imagem conta como processada. Image Processor processa uma imagem quando a constrói, e não cada vez que o cache a serve, então uma imagem derivada que permanece em cache é processada uma vez. O cache pode remover uma cópia pouco acessada antes do fim da idade máxima dela, e a próxima requisição por essa imagem é processada de novo. Para a métrica e a tarifa, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#image-processor). --- ## Onde Image Processor para -Image Processor lê uma imagem de origem a partir da origem e retorna uma derivada sem salvá-la como um ativo da conta. Não é possível fazer upload de imagens para Image Processor: a imagem de origem permanece onde já está, e o cache guarda as imagens derivadas. Um workflow que precisa manter um arquivo transformado precisa salvar a resposta por conta própria. +Image Processor lê uma imagem de origem a partir da origem e retorna uma derivada sem salvá-la na conta. Não é possível fazer upload de imagens para Image Processor: a imagem de origem permanece onde já está, e o cache guarda as imagens derivadas. Um workflow que precisa manter um arquivo transformado precisa salvar a resposta por conta própria. -O que a string `ims` pode expressar e o tamanho da imagem limitam a transformação. As operações que a string aceita estão em [Parâmetros de URL do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/parametros-de-url/), e o tamanho e as dimensões máximas estão em [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#image-processor). +O que `ims` pode expressar e o tamanho da imagem limitam a transformação. As operações que `ims` aceita estão em [Parâmetros de URL do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/parametros-de-url/), e o tamanho e as dimensões máximas estão em [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#image-processor). Vale nomear uma distinção, porque duas superfícies compartilham um nome. [WASM Image Processor](/pt-br/documentacao/devtools/azion-lib/wasm-image-processor/) é uma biblioteca WebAssembly que processa imagens dentro de uma [Function](/pt-br/documentacao/plataforma/functions/). Ela é executada no código dessa Function, separada do recurso da plataforma Image Processor e de tudo o que esta página descreve. @@ -80,8 +84,8 @@ Vale nomear uma distinção, porque duas superfícies compartilham um nome. [WAS Os headers e os behaviors de Image Processor, incluindo os headers de resposta de uma imagem processada. - Cada operação que a query string ims expressa, com os valores que cada uma aceita. + Cada operação que o parâmetro ims expressa, com os valores que cada uma aceita. A regra que envia requisições de imagens ao Image Processor, passo a passo. - O controle de query string que dá a cada string ims uma cache key própria. + O controle de query string que dá a cada valor de ims uma cache key própria. diff --git a/apps/docs/src/content/docs/pt-br/pages/build/image-processor/configuracoes.mdx b/apps/docs/src/content/docs/pt-br/pages/build/image-processor/configuracoes.mdx index 61e22e8d87..57e534c124 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/image-processor/configuracoes.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/image-processor/configuracoes.mdx @@ -13,7 +13,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -[Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) é um recurso da plataforma que constrói uma imagem derivada a partir da imagem de origem na origem de uma [Application](/pt-br/documentacao/plataforma/applications/). Ele vem desativado em uma Application nova, e cada Application o ativa separadamente. Com Image Processor ativado, uma requisição de imagem pode carregar uma query string `ims` que descreve uma transformação. Esta página traz o campo, a flag e a interface que define cada um, além dos behaviors, campos de cache, headers e datasets que Image Processor alcança. +[Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) é um recurso da plataforma que constrói uma imagem derivada a partir da imagem de origem no servidor de origem de uma [Application](/pt-br/documentacao/plataforma/applications/). Ele vem desativado em uma Application nova, e cada Application o ativa separadamente. Com Image Processor ativado, uma requisição de imagem pode carregar um parâmetro de query string `ims` que descreve uma transformação. --- @@ -23,13 +23,13 @@ Cinco interfaces definem o mesmo switch, e o switch pertence à Application: uma | Interface | Onde você define | Campo ou flag | | --- | --- | --- | -| Azion Console | O grupo **Default Modules** da seção **Modules**, na aba **Main Settings** de uma Application | O switch **Image Processor**, com o texto de ajuda "Enable dynamic image editing options." | +| Azion Console | Aba **Main Settings** › **Modules** › **Default Modules** de uma Application | O switch **Image Processor** | | Azion API v4 | `PATCH /v4/workspace/applications/` | `modules.image_processor.enabled` | | Azion API v3 | `PATCH https://api.azionapi.net/edge_applications/` | `image_optimization` | | [Azion CLI](/pt-br/documentacao/devtools/cli/) | `azion create application` e `azion update application` | `--image-processor` | | [`azion.config.js`](/pt-br/documentacao/devtools/cli/azion-config-js/) e [Azion Lib](/pt-br/documentacao/devtools/azion-lib/) | Uma entrada de `applications`, uma por Application | `imageProcessorEnabled` | -`modules.image_processor.enabled` e `imageProcessorEnabled` são booleanos, e os dois assumem `false` por padrão. A flag da Azion CLI recebe uma string: `--image-processor true`. Em Azion Console, o switch é salvo com **Save**. +`modules.image_processor.enabled` e `imageProcessorEnabled` são booleanos, e os dois assumem `false` por padrão. A flag da Azion CLI recebe uma string: `--image-processor true`. Em Azion Console, o switch carrega o texto de ajuda "Enable dynamic image editing options." e é salvo com **Save**. API v4 carrega o switch no objeto `modules` da Application: @@ -49,23 +49,49 @@ O mesmo objeto `modules` carrega `application_accelerator`, `cache` e `functions ## Behaviors do Rules Engine -Uma regra para imagens pode carregar três behaviors do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/). Só **Optimize Images** é necessário para processar uma imagem, e ele exige Image Processor ativado na Application que executa a regra. +Uma regra para imagens pode carregar três behaviors do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/). Só _Optimize Images_ é necessário para processar uma imagem, e ele exige Image Processor ativado na Application que executa a regra. | Behavior | Fase | Tipo na API | O que faz | | --- | --- | --- | --- | -| **Optimize Images** | **Request Phase** | `optimize_images` | Aplica Image Processor à requisição correspondente. Não recebe atributos. | -| **Set Cache Policy** | **Request Phase** | `set_cache_policy` | Aplica um cache setting à requisição correspondente. | -| **Add Request Header** | **Request Phase** | `add_request_header` | Adiciona um header à requisição. | +| _Optimize Images_ | **Request Phase** | `optimize_images` | Aplica Image Processor à requisição correspondente. Não recebe atributos. | +| _Set Cache Policy_ | **Request Phase** | `set_cache_policy` | Aplica um cache setting à requisição correspondente. | +| _Add Request Header_ | **Request Phase** | `add_request_header` | Adiciona um header à requisição. | -Em **Set Cache Policy**, `attributes.value` carrega o id do cache setting, e no Azion Console você o seleciona em um segundo dropdown. Em **Add Request Header**, `attributes.value` assume o formato `Field: value`, como `Accept: image/webp` ou `Accept: image/avif`. +Em _Set Cache Policy_, `attributes.value` carrega o id do cache setting, e no Azion Console você o seleciona em um segundo dropdown. Em _Add Request Header_, `attributes.value` assume o formato `Field: value`, como `Accept: image/webp` ou `Accept: image/avif`. Um critério da mesma regra carrega `variable`, `operator`, `conditional` e `argument`. Uma regra que corresponde a requisições de imagem lê `${request_uri}` ou `${uri}` com o operador `matches`, usando um argumento como `\.(jpg|jpeg|gif|bmp|png|ico|webp|avif)`. `${request_uri}` exige Application Accelerator na Application: enquanto Application Accelerator está desativado, a API recusa uma regra que o lê e retorna o erro `25047`. `${uri}` não depende de nenhum recurso da plataforma. +Para processar cada requisição por um path de imagem e armazenar em cache cada imagem derivada, envie esta regra como corpo de `POST /v4/workspace/applications/{application_id}/request_rules`: + +```json +{ + "name": "Optimize images", + "description": "Apply the cache setting and optimize images", + "active": true, + "criteria": [ + [ + { + "conditional": "if", + "variable": "${request_uri}", + "operator": "matches", + "argument": "\\.(jpg|jpeg|gif|bmp|png|ico|webp|avif)" + } + ] + ], + "behaviors": [ + { "type": "set_cache_policy", "attributes": { "value": } }, + { "type": "optimize_images" } + ] +} +``` + +Substitua `` pelo id do cache setting que guarda as imagens derivadas. + --- ## Variação de cache -Uma imagem derivada é armazenada em cache sob uma cache key própria quando o cache setting dela varia o cache por `ims`, porque a cache key passa a incluir a query string `ims` depois de `@@`. Uma variação com um formato convertido também carrega o formato do arquivo no fim da key, sem separador, como em `httpsstatic.example.com/static/images/image_1.jpg@@?ims=880xwebp`. +Uma imagem derivada recebe uma cache key própria quando o cache setting dela varia o cache por `ims`. A key passa a carregar o valor de `ims` depois de `@@`, e uma cópia com um formato convertido também carrega o formato do arquivo no fim da key, sem separador, como em `httpsstatic.example.com/static/images/image_1.jpg@@?ims=880xwebp`. Variar o cache por query string usa um campo do [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/): `cache_vary_by_querystring`, sob `modules.application_accelerator` em um cache setting. Então, variar o cache por `ims` exige Application Accelerator, enquanto processar uma imagem não o exige. @@ -73,9 +99,9 @@ No Azion Console, cada campo corresponde a um controle do painel **Cache vary by | Campo | Controle no Console | O que define | | --- | --- | --- | -| `cache_vary_by_querystring.behavior` | **Behavior** | Como o cache trata os parâmetros da query string. O dropdown oferece _Allowlist_, _Denylist_, _Ignore_ e _All_. | -| `cache_vary_by_querystring.fields` | **Fields** | Os parâmetros de query string considerados para a variação de cache, um por linha. | -| `cache_vary_by_querystring.sort_enabled` | **Sort** | Se os parâmetros de query string são ordenados, de forma que o comportamento do cache não dependa da ordem em que chegam. | +| `cache_vary_by_querystring.behavior` | **Behavior** | O modo que decide como a query string varia a key: _Allowlist_, _Denylist_, _Ignore_ ou _All_. | +| `cache_vary_by_querystring.fields` | **Fields** | Os argumentos de query string aos quais o modo se aplica, um por linha. | +| `cache_vary_by_querystring.sort_enabled` | **Sort** | Se toda ordem dos argumentos se agrupa sob uma única key, em ordem alfabética. | Um cache setting para imagens carrega `ims` em `fields`. Para o restante dos campos que um cache setting carrega, incluindo a idade máxima do objeto em cache, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/). Para os demais campos que Application Accelerator libera, consulte [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/). @@ -94,11 +120,11 @@ Azion retorna dois headers em uma resposta que Image Processor processou. ## Dados de uso e eventos -Azion reporta a atividade de Image Processor em seis superfícies: quatro no Azion Console, duas em Real-Time Metrics e duas em Real-Time Events, e duas em GraphQL. +Azion reporta a atividade de Image Processor em seis superfícies: duas em Real-Time Metrics e duas em Real-Time Events, no Console, e duas em GraphQL. | Superfície | O que carrega | | --- | --- | -| A aba **Image Processor** de [Real-Time Metrics](/pt-br/documentacao/plataforma/real-time-metrics/) | Métricas das requisições feitas às imagens processadas por Image Processor na sua conta, nos gráficos Total Requests e Total Requests per Second. | +| A aba **Image Processor** de [Real-Time Metrics](/pt-br/documentacao/plataforma/real-time-metrics/) | Os gráficos Total Requests e Total Requests per Second das imagens que Image Processor processou na sua conta. | | O dashboard **Bandwidth Saving** na aba **Applications** de Real-Time Metrics | Os bytes que Image Processor economizou nas imagens que processou e entregou. | | O dataset **Image Processor** de [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/) | Os registros de eventos das requisições feitas a Applications que usam Image Processor. | | O campo **Proxy Upstream** da fonte de dados Tiered Cache de Real-Time Events | `ims_http`, o valor que o campo assume quando Image Processor é o upstream da camada de Tiered Cache. | @@ -121,7 +147,7 @@ WASM Image Processor é uma biblioteca WebAssembly que processa imagens dentro d Ative Image Processor e solicite uma imagem transformada pela primeira vez. Como o formato entregue é escolhido, como uma imagem derivada é armazenada em cache e onde Image Processor para. - A gramática da query string `ims` que estas configurações ativam. + A gramática do parâmetro `ims` que estas configurações ativam. As etapas que ativam Image Processor e criam a regra, interface por interface. diff --git a/apps/docs/src/content/docs/pt-br/pages/build/image-processor/parametros-de-url.mdx b/apps/docs/src/content/docs/pt-br/pages/build/image-processor/parametros-de-url.mdx index 5dc297b35b..9035680a49 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/image-processor/parametros-de-url.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/image-processor/parametros-de-url.mdx @@ -1,7 +1,7 @@ --- title: Parâmetros de URL do Image Processor description: >- - Consulte a query string ims: redimensionamento, recorte, rotação, + Consulte o parâmetro ims: redimensionamento, recorte, rotação, qualidade, marca d'água, conversão de formato e preenchimento, com os valores aceitos. meta_tags: 'image processor, ims, query string, resize, crop, rotate, watermark, format conversion, fill' @@ -13,7 +13,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -A query string `ims` carrega a transformação que [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) aplica a uma imagem. Uma única string pode conter um redimensionamento, um recorte e uma cadeia de filtros. Image Processor retorna uma imagem derivada, construída a partir da imagem de origem hospedada no servidor de origem, e lê a imagem de origem sem alterá-la. Esta página traz a sintaxe de cada operação, os valores que os seus argumentos aceitam e um resultado renderizado. +O parâmetro de query string `ims` carrega a transformação que [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) aplica a uma imagem. Um único valor de `ims` pode conter um redimensionamento, um recorte e uma cadeia de filtros. Image Processor retorna uma imagem derivada, construída a partir da imagem de origem hospedada no servidor de origem, e lê a imagem de origem sem alterá-la. --- @@ -170,7 +170,7 @@ A imagem abaixo carrega `?ims=fit-in/400x400/filters:fill(gray)`: ## Filtros combinados -Uma única string `ims` pode carregar mais de um filtro. Os filtros ficam dentro de um único grupo `filters:`, e um `:` separa cada um do próximo, como em `filters:filter1(arg1):filter2(arg2)`. +Um único valor de `ims` pode carregar mais de um filtro. Os filtros ficam dentro de um único grupo `filters:`, e um `:` separa cada um do próximo, como em `filters:filter1(arg1):filter2(arg2)`. | Segmento | Exemplo | O que faz | | --- | --- | --- | @@ -200,7 +200,7 @@ Image Processor aceita estes formatos de imagem de origem: Um navegador exibe uma imagem derivada em WEBP ou AVIF somente quando suporta esse formato. Para os navegadores que suportam cada um, consulte [Suporte de navegadores para WEBP](https://caniuse.com/webp) e [Suporte de navegadores para AVIF](https://caniuse.com/avif). -Image Processor também converte um formato sem o parâmetro `ims` na requisição. Ele detecta quais formatos o navegador suporta e, quando possível, converte a imagem para um deles, como WEBP ou AVIF. Imagens BMP são convertidas para JPEG ou WEBP dependendo do mesmo suporte de navegador. Para mais informações, consulte [Entrega de imagens](/pt-br/documentacao/plataforma/applications/image-processor/entrega-de-imagens/). +Image Processor também pode converter uma imagem sem o parâmetro `ims` na requisição, para um formato que o navegador suporta, como explica [Negociação de formato](/pt-br/documentacao/plataforma/applications/image-processor/entrega-de-imagens/#negociacao-de-formato). --- diff --git a/apps/docs/src/content/docs/pt-br/pages/build/image-processor/primeiros-passos.mdx b/apps/docs/src/content/docs/pt-br/pages/build/image-processor/primeiros-passos.mdx index b51315d038..9b728ca9a3 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/image-processor/primeiros-passos.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/image-processor/primeiros-passos.mdx @@ -15,14 +15,21 @@ import DocStep from '@aziontech/webkit/doc-step' import Tabs from '~/components/webkit/Tabs.vue' import Code from '~/components/webkit/CodeBlock.vue' -Este guia conduz você pela requisição da sua primeira imagem derivada a partir de uma Application. Ao final, você terá: +Este guia conduz você pela requisição da sua primeira imagem derivada, a imagem que Image Processor constrói a partir de um arquivo no seu servidor de origem. Ao final, você terá: - [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) ativado em uma Application. -- Um cache setting que armazena cada transformação como um objeto próprio. +- Um cache setting que armazena cada transformação como uma cópia separada. - Uma regra do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) que envia requisições de imagem ao Image Processor. - Uma imagem redimensionada retornada a partir de uma URL que você escreveu. -Três entidades e uma URL produzem esse resultado, nesta ordem. A **Application** tem Image Processor ativado. O **cache setting** pertence à Application e faz o cache armazenar duas transformações diferentes como dois objetos diferentes. A **regra** pertence à Application, corresponde a requisições de imagem e aplica tanto o cache setting quanto o behavior _Optimize Images_. A URL da imagem carrega então a transformação na própria query string `ims`. Uma requisição à qual nenhuma regra corresponde é entregue sem processamento, então é a regra que dá sentido à query string. +Três entidades e uma URL produzem esse resultado, nesta ordem: + +1. A **Application** tem Image Processor ativado. +2. O **cache setting** pertence à Application e faz o cache armazenar duas transformações diferentes como duas cópias separadas. +3. A **regra** pertence à Application, corresponde a requisições de imagem e aplica tanto o cache setting quanto o behavior _Optimize Images_. +4. A URL da imagem carrega a transformação no seu parâmetro de query string `ims`. + +Uma requisição à qual nenhuma regra corresponde é entregue sem processamento, então é a regra que dá sentido a `ims`. --- @@ -72,9 +79,9 @@ Três entidades e uma URL produzem esse resultado, nesta ordem. A **Application* ## Ative Image Processor e Application Accelerator -Image Processor é um recurso da plataforma que vem desativado em uma Application nova. Esta etapa ativa dois recursos da plataforma. +Image Processor, o recurso da plataforma que constrói imagens derivadas sob demanda, vem desativado em uma Application nova. Esta etapa o ativa, junto com um segundo recurso da plataforma. -[Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) é o segundo por dois motivos. O campo que varia o cache por uma query string pertence a ele, e o cache setting usa esse campo. A regra deste guia também lê `${request_uri}`, e a Azion recusa uma regra que o lê enquanto Application Accelerator está desativado. Processar uma imagem não exige Application Accelerator, mas armazenar cada transformação separadamente em cache exige. +Esta etapa também ativa [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/), por dois motivos. O campo que varia o cache por uma query string pertence a ele, e o cache setting usa esse campo. A regra deste guia também lê `${request_uri}`, e a Azion recusa uma regra que o lê enquanto Application Accelerator está desativado. Processar uma imagem não exige Application Accelerator, mas armazenar cada transformação separadamente em cache exige. @@ -87,7 +94,7 @@ Para ativar os dois recursos da plataforma pelo Azion Console: - Acesse [Azion Console](https://console.azion.com/) > **Applications** > **sua Application**. + Acesse [Azion Console](https://console.azion.com/) > **Applications** > sua Application. @@ -179,9 +186,13 @@ A Application agora tem os dois recursos da plataforma ativados, e o behavior _O +:::caution[Atenção] +Ativar Application Accelerator pode gerar custos relacionados ao uso. Para mais informações, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#application-accelerator). +::: + --- -## Crie um cache setting que varia pela query string ims +## Crie um cache setting que varia pelo parâmetro ims Sem esta etapa, o cache não consegue diferenciar uma transformação de outra. Ele pode responder a uma requisição de imagem de 400 pixels com uma de 200 pixels. @@ -196,7 +207,7 @@ Para criar o cache setting pelo Azion Console: - Acesse [Azion Console](https://console.azion.com/) > **Applications** > **sua Application**. + Acesse [Azion Console](https://console.azion.com/) > **Applications** > sua Application. @@ -216,7 +227,7 @@ Para criar o cache setting pelo Azion Console: Na seção **Cache**, em **Max Age**, digite `31536000`. - + O painel fica na seção **Application Accelerator**. @@ -231,7 +242,7 @@ Para criar o cache setting pelo Azion Console: -A Application agora tem um cache setting que armazena um objeto por valor distinto de `ims`. +A Application agora tem um cache setting que armazena uma cópia separada para cada valor distinto de `ims`. @@ -239,7 +250,7 @@ A Application agora tem um cache setting que armazena um objeto por valor distin ### CLI -O comando da Azion CLI envia o body inteiro a partir de um arquivo, porque nenhuma flag de criação define o `max_age` do cache nem o `sort_enabled`. +Nenhuma flag de criação define o `max_age` do cache nem o `sort_enabled`, então o comando envia o corpo inteiro a partir de um arquivo. Para criar o cache setting com a Azion CLI: @@ -279,14 +290,16 @@ O comando da Azion CLI envia o body inteiro a partir de um arquivo, porque nenhu - --cache-setting-id 123464 --format json`} /> + Substitua `` pelo id que o comando de criação imprimiu: + + --cache-setting-id --format json`} /> A saída informa a allowlist de `ims` e a idade máxima que o arquivo definiu. -A Application agora tem um cache setting que armazena um objeto por valor distinto de `ims`. Registre o id que o comando imprimiu, porque a regra o aplica. Para todas as flags que o comando aceita, consulte [Azion CLI cache-setting](/pt-br/documentacao/devtools/cli/recursos/cache-setting/). +A Application agora tem um cache setting que armazena uma cópia separada para cada valor distinto de `ims`. Registre o id que o comando imprimiu, porque a regra o aplica. Para todas as flags que o comando aceita, consulte [Azion CLI cache-setting](/pt-br/documentacao/devtools/cli/recursos/cache-setting/). @@ -294,7 +307,7 @@ A Application agora tem um cache setting que armazena um objeto por valor distin ### API -Uma requisição carrega o comportamento de cache e a allowlist de query string juntos. +Uma requisição carrega o behavior de cache e a allowlist de query string juntos. Para criar o cache setting com a Azion API: @@ -333,7 +346,7 @@ Uma requisição carrega o comportamento de cache e a allowlist de query string -A Application agora tem um cache setting que armazena um objeto por valor distinto de `ims`. +A Application agora tem um cache setting que armazena uma cópia separada para cada valor distinto de `ims`. @@ -345,7 +358,7 @@ Para o restante dos campos que um cache setting carrega, incluindo por quanto te ## Crie uma regra que envia as requisições de imagem ao Image Processor -A regra é o que converte a query string em uma transformação. Ela corresponde a requisições de paths de imagem, aplica o cache setting que você criou e carrega o behavior _Optimize Images_. +A regra é o que converte `ims` em uma transformação. Ela corresponde a requisições de paths de imagem, aplica o cache setting que você criou e carrega o behavior _Optimize Images_. @@ -358,7 +371,7 @@ Para criar a regra pelo Azion Console: - Acesse [Azion Console](https://console.azion.com/) > **Applications** > **sua Application**. + Acesse [Azion Console](https://console.azion.com/) > **Applications** > sua Application. @@ -382,7 +395,12 @@ Para criar a regra pelo Azion Console: - Nos behaviors, selecione **Set Cache Policy** e escolha o cache setting `images`. + Nos behaviors, selecione _Set Cache Policy_. + + + + + Como cache setting de _Set Cache Policy_, selecione `images`. @@ -398,12 +416,12 @@ Toda requisição para um path com uma dessas extensões agora recebe o cache se ### CLI -Os critérios carregam `${request_uri}`, que um shell expande, e o argumento carrega barras invertidas, então a regra vai em um arquivo. +Os critérios carregam `${request_uri}`, que um shell expande, e o argumento carrega barras invertidas, então a regra vai em um arquivo. Para criar a regra com a Azion CLI: - Salve o conteúdo a seguir como `rule.json`, com o id do seu cache setting no behavior `set_cache_policy`: + Salve o conteúdo a seguir como `rule.json` e substitua `` pelo id do seu cache setting: } }, { "type": "optimize_images" } ] }`} /> @@ -449,12 +467,12 @@ Toda requisição para um path com uma dessas extensões agora recebe o cache se ### API -Os critérios carregam `${request_uri}`, que um shell expande, e o argumento carrega barras invertidas, então o body é enviado a partir de um arquivo. +Os critérios carregam `${request_uri}`, que um shell expande, e o argumento carrega barras invertidas, então o corpo é enviado a partir de um arquivo. Para criar a regra com a Azion API: - Salve o conteúdo a seguir como `rule.json`, com o id do seu cache setting no behavior `set_cache_policy`: + Salve o conteúdo a seguir como `rule.json` e substitua `` pelo `data.id` que a criação do cache setting retornou: } }, { "type": "optimize_images" } ] }`} /> @@ -503,7 +521,7 @@ Toda requisição para um path com uma dessas extensões agora recebe o cache se :::note[nota] -Esta parte é opcional. Um behavior **Add Request Header** com `Accept: image/webp` na mesma regra faz a conversão automática entregar WEBP a toda requisição à qual a regra corresponde, inclusive a uma cujo navegador pediu PNG. Adicione-o somente quando todos os clientes desses paths exibirem WEBP. Na Azion CLI e na API, é um behavior do tipo `add_request_header`, cujos `attributes` carregam `"value": "Accept: image/webp"`. Para os campos do behavior, consulte [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/). +Um behavior opcional _Add Request Header_ com `Accept: image/webp` na mesma regra faz a conversão automática entregar WEBP a toda requisição à qual a regra corresponde, inclusive a uma cujo navegador pediu PNG. Adicione-o somente quando todos os clientes desses paths exibirem WEBP. Na Azion CLI e na API, é um behavior do tipo `add_request_header`, cujos `attributes` carregam `"value": "Accept: image/webp"`. Para os campos do behavior, consulte [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/). ::: --- @@ -512,7 +530,7 @@ Esta parte é opcional. Um behavior **Add Request Header** com `Accept: image/we Peça uma largura e veja a resposta mudar. -Requisite uma das suas imagens com uma query string `ims`, substituindo o host e o path pelos seus próprios: +Requisite uma das suas imagens com um parâmetro `ims` na query string, substituindo o host e o path pelos seus próprios: - + diff --git a/apps/docs/src/content/docs/pt-br/pages/build/image-processor/visao-geral.mdx b/apps/docs/src/content/docs/pt-br/pages/build/image-processor/visao-geral.mdx index 171d0c86b0..347f8f3911 100644 --- a/apps/docs/src/content/docs/pt-br/pages/build/image-processor/visao-geral.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/build/image-processor/visao-geral.mdx @@ -1,6 +1,6 @@ --- title: Image Processor -description: Redimensione, recorte, filtre e converta imagens sob demanda com Image Processor, a partir de uma imagem de origem na origem de uma Application. +description: Redimensione, recorte, filtre e converta imagens sob demanda com Image Processor, a partir de uma imagem de origem no servidor de origem de uma Application. meta_tags: 'image processor, ims, derived image, source image, resize, crop, filters, webp, avif, optimize images, applications' namespace: documentation_products_image_optimization permalink: /documentacao/plataforma/applications/image-processor/ @@ -10,18 +10,16 @@ import DocButton from '~/components/webkit/DocButton.vue' import DocCardGroup from '@aziontech/webkit/doc-card-group' import DocCard from '@aziontech/webkit/doc-card' -**Image Processor** é um recurso da plataforma que constrói uma imagem nova, a imagem derivada, a partir de uma imagem na origem de uma [Application](/pt-br/documentacao/plataforma/applications/). A transformação de imagens sob demanda é um modelo de entrega em que o servidor constrói cada variante de uma imagem no momento da requisição. A URL da requisição descreve a variante, como uma largura, um recorte, uma qualidade ou um formato. Cada variante vem do único original, então o original é o único arquivo que você armazena e atualiza. - -Em uma Application, Image Processor lê a imagem de origem, o arquivo na origem, sem alterá-la. A query string `ims` da requisição descreve a imagem derivada, como `?ims=fit-in/400x400`. Mesmo sem a query string `ims`, Image Processor pode converter uma imagem para um formato que o navegador aceita. Image Processor processa somente as requisições às quais uma regra da Request Phase com o behavior _Optimize Images_ corresponde, e você escreve essa regra no [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) da Application. Use Image Processor para entregar uma imagem em vários tamanhos, recortes, qualidades ou formatos, como WEBP para os navegadores que o aceitam, sem um arquivo por variante. +**Image Processor** é um recurso da plataforma que constrói imagens derivadas de imagens da origem na infraestrutura distribuída da Azion, para requisições recebidas por [Applications](/pt-br/documentacao/plataforma/applications/). A transformação de imagens sob demanda é um modelo de entrega em que o servidor constrói cada variante na requisição, conforme descrito na URL. Use Image Processor para servir uma imagem em vários tamanhos, recortes, qualidades ou formatos, como WEBP para navegadores que o aceitam, de um arquivo. - + --- ## Caminho da requisição -Uma query string `ims` não transforma uma imagem por si só: antes, uma regra com o behavior [Optimize Images](/pt-br/documentacao/plataforma/applications/rules-engine/#optimize-images) precisa corresponder à requisição. Ativar Image Processor em uma Application apenas disponibiliza esse behavior para as regras dela. +O parâmetro de query string `ims` não transforma uma imagem por si só: antes, uma regra com o behavior [Optimize Images](/pt-br/documentacao/plataforma/applications/rules-engine/#optimize-images) precisa corresponder à requisição. Ativar Image Processor em uma Application apenas disponibiliza esse behavior para as regras do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) dela. As setas sólidas levam a requisição, e as setas pontilhadas levam a resposta. Cada rótulo começa com o número do seu passo abaixo. @@ -34,7 +32,7 @@ flowchart TD IP["Image Processor"] Origin[["servidor de origem"]] Client -->|"1. requisição por uma imagem"| App - App -.->|"2. sem regra: imagem sem processamento"| Client + App -.->|"2. sem regra: entregue sem processamento"| Client App -->|"3. cache setting"| Cache Cache -.->|"4. imagem derivada em cache"| App App -->|"5. sem cópia em cache"| IP @@ -44,74 +42,25 @@ flowchart TD App -.->|"4, 5. imagem derivada"| Client ``` -1. Uma requisição para um path que contém uma imagem chega à Application, que executa as suas regras da Request Phase. Uma regra para imagens compara `${uri}`, ou `${request_uri}` com [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) ativo, com um argumento como `\.(jpg|jpeg|gif|bmp|png|ico|webp|avif)`. -2. Quando nenhuma regra com _Optimize Images_ corresponde à requisição, a imagem de origem é entregue sem processamento, mesmo quando a requisição carrega `ims`. -3. Uma regra que corresponde à requisição aplica os seus behaviors. _Optimize Images_ marca a requisição para Image Processor. Quando a regra também carrega _Set Cache Policy_, esse behavior aplica o [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) que guarda a imagem derivada. Uma regra pode carregar _Optimize Images_ sozinho, porque o behavior não recebe argumento. +1. Uma requisição para um path que contém uma imagem chega à Application, que executa as suas regras da Request Phase, como uma regra com _Optimize Images_ que corresponde a requisições de imagem. Para criar essa regra passo a passo, consulte [Configure Image Processor em uma aplicação](/pt-br/documentacao/guias/performance-e-confiabilidade/otimizacao-de-entrega/processar-imagens/). +2. Quando nenhuma regra com _Optimize Images_ corresponde à requisição, a imagem de origem, o arquivo no servidor de origem, é entregue sem processamento. +3. Uma regra que corresponde à requisição aplica os seus behaviors. _Optimize Images_ aplica Image Processor à requisição. Quando a regra também carrega _Set Cache Policy_, esse behavior aplica o [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) que guarda a imagem derivada. Uma regra pode carregar _Optimize Images_ sozinho, porque o behavior não recebe argumento. 4. Quando a imagem derivada já está em cache, [Cache](/pt-br/documentacao/plataforma/applications/cache/) a entrega sem processamento. -5. Caso contrário, Image Processor lê a imagem de origem a partir da origem e aplica a query string `ims` a ela. A imagem derivada é entregue. O cache da Application só a armazena quando a regra aplica um cache setting com _Set Cache Policy_. Sem esse cache setting, toda requisição chega ao Image Processor, que responde a uma transformação repetida a partir do próprio cache. - -Quando uma regra com _Optimize Images_ corresponde a um path que não retorna uma imagem, a requisição falha com um `400` vazio, então os critérios da regra precisam corresponder somente a paths de imagem. Para criar essa regra passo a passo, consulte [Configure Image Processor em uma aplicação](/pt-br/documentacao/guias/performance-e-confiabilidade/otimizacao-de-entrega/processar-imagens/). +5. Caso contrário, Image Processor lê a imagem de origem sem alterá-la e aplica `ims` a ela, como em `?ims=fit-in/400x400`. A imagem derivada é entregue. O cache da Application só a armazena quando a regra aplica um cache setting com _Set Cache Policy_. Sem esse cache setting, toda requisição chega ao Image Processor, que responde a uma transformação repetida a partir do próprio cache. Para saber como o formato entregue é escolhido, como o cache diferencia as imagens derivadas e onde Image Processor para, consulte [Entrega de imagens](/pt-br/documentacao/plataforma/applications/image-processor/entrega-de-imagens/). --- -## Estrutura da regra - -Image Processor age por meio de uma regra da Request Phase que carrega o behavior _Optimize Images_. Para processar cada requisição por um path de imagem e armazenar em cache cada imagem derivada, envie esta regra como corpo de `POST /v4/workspace/applications//request_rules`: - -```json -{ - "name": "Optimize images", - "description": "Apply the cache setting and optimize images", - "active": true, - "criteria": [ - [ - { - "conditional": "if", - "variable": "${request_uri}", - "operator": "matches", - "argument": "\\.(jpg|jpeg|gif|bmp|png|ico|webp|avif)" - } - ] - ], - "behaviors": [ - { "type": "set_cache_policy", "attributes": { "value": } }, - { "type": "optimize_images" } - ] -} -``` - -- `criteria` compara o path com uma lista de extensões de imagem por meio de `matches`. `${request_uri}` exige Application Accelerator, e `${uri}` corresponde aos mesmos paths sem ele. -- `optimize_images` não recebe atributos e marca a requisição para Image Processor. Ele exige Image Processor ativo na Application que executa a regra. -- `set_cache_policy` aplica o cache setting cujo ID está em `attributes.value`, e esse cache setting armazena cada imagem derivada. Com `ims` nos `fields` da allowlist `cache_vary_by_querystring` dele, cada string `ims` distinta recebe uma cache key própria. Esse campo pertence ao Application Accelerator, então exige Application Accelerator ativo. -- Cada requisição então carrega a sua transformação na URL, como `?ims=400x`. Uma resposta processada carrega `x-ims: Enabled`, e `x-original-image-size` carrega o tamanho da imagem de origem antes da transformação. - ---- - -## Escopo e limites - -- **Application**: Image Processor vem desativado em uma Application nova, e cada Application o ativa separadamente, no seu campo `modules.image_processor.enabled` na API. Mesmo ativo, Image Processor processa somente as requisições às quais uma regra com _Optimize Images_ corresponde. [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#recursos-da-plataforma) mostra onde ativá-lo no Azion Console e na API. -- **Operações**: uma string `ims` pode carregar um redimensionamento, um recorte e uma cadeia de filtros. As operações são redimensionamento, recorte, rotação, qualidade, marca d'água, conversão de formato e preenchimento, e `fit-in` encaixa uma imagem em uma área sem ampliá-la. Para a sintaxe e os valores que cada uma aceita, consulte [Parâmetros de URL](/pt-br/documentacao/plataforma/applications/image-processor/parametros-de-url/). -- **Posição do parâmetro**: `ims` pode ficar em qualquer posição da query string. Um valor de `ims` que Image Processor não consegue interpretar retorna a imagem de origem sem transformação. -- **Formatos**: Image Processor lê JPEG, GIF, PNG, BMP, ICO, WEBP e AVIF. Mesmo sem nenhum parâmetro `ims`, ele pode converter uma imagem para um formato que o navegador aceita, como WEBP ou AVIF, e converte uma imagem BMP para JPEG ou WEBP. Um filtro `filters:format()` retorna o formato que ele nomeia, qualquer que seja o header `Accept` da requisição. Para saber como o formato entregue é escolhido, consulte [Entrega de imagens](/pt-br/documentacao/plataforma/applications/image-processor/entrega-de-imagens/#negociacao-de-formato). -- **Cache**: quando `ims` está na allowlist do cache setting, cada string `ims` distinta, em cada formato entregue, é um objeto armazenado separado. Uma página que pede quatro larguras fixas armazena quatro objetos por formato entregue, enquanto uma página que pede larguras arbitrárias armazena um por largura e formato. Quando uma imagem derivada já está em cache, ela é entregue sem processamento. Para as práticas, consulte [Boas práticas de Applications](/pt-br/documentacao/plataforma/applications/boas-praticas/#image-processor). -- **Armazenamento**: Image Processor retorna cada imagem derivada sem salvá-la como um ativo da conta, e não é possível fazer upload de imagens para Image Processor. O cache guarda as imagens derivadas, e a imagem de origem permanece onde já está. Um workflow que precisa manter um arquivo transformado salva a resposta por conta própria. -- **Vizinhos**: [WASM Image Processor](/pt-br/documentacao/devtools/azion-lib/wasm-image-processor/) é uma biblioteca WebAssembly que processa imagens dentro de uma [Function](/pt-br/documentacao/plataforma/functions/). Ela é executada no código dessa Function, separada do recurso da plataforma Image Processor e das configurações dele. -- **Interfaces**: você ativa Image Processor na aba **Main Settings** de uma Application no [Azion Console](https://console.azion.com/) e pela [Azion API](https://api.azion.com/) em `/v4/workspace/applications/`. [Azion CLI](/pt-br/documentacao/devtools/cli/) o define com `--image-processor` em `azion create application` ou `azion update application`. [`azion.config.js`](/pt-br/documentacao/devtools/cli/azion-config-js/) e [Azion Lib](/pt-br/documentacao/devtools/azion-lib/) o definem com `imageProcessorEnabled`. Para cada campo, flag, behavior e header, consulte [Configurações do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/configuracoes/). -- **Observabilidade**: no Azion Console, [Real-Time Metrics](/pt-br/documentacao/plataforma/real-time-metrics/) tem uma aba **Image Processor** com gráficos de requisições, e [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/) tem um dataset **Image Processor**, que exige Image Processor ativo. -- **Limites**: uma imagem aceita até 150 MB, 3840 pixels de largura e 2160 pixels de altura. Para cada limite, consulte [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#image-processor) e, para os valores, consulte [Preços](/pt-br/documentacao/fundamentos/precos/#image-processor). A página [Preços da Azion](https://www.azion.com/pt-br/precos/) lista o que cada plano inclui. -- **Termos**: o [glossário de Applications](/pt-br/documentacao/plataforma/applications/glossario/) define as palavras às quais as páginas do Image Processor dão um significado específico, como imagem derivada, imagem de origem, recorte automático e `fit-in`. - ---- - ## Próximos passos - + + - + + diff --git a/apps/docs/src/content/docs/pt-br/pages/hubs/guias/applications.mdx b/apps/docs/src/content/docs/pt-br/pages/hubs/guias/applications.mdx index 1bfc97fc39..4c1cb88e3c 100644 --- a/apps/docs/src/content/docs/pt-br/pages/hubs/guias/applications.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/hubs/guias/applications.mdx @@ -1,10 +1,10 @@ --- title: Guias e tutoriais de Applications -description: Todos os guias e tutoriais de Applications e dos recursos da plataforma aninhados nele. +description: Encontre todos os guias e tutoriais de Applications e dos recursos da plataforma aninhados nele. meta_tags: 'applications, guias, tutoriais' namespace: documentation_products_applications_guides permalink: /documentacao/plataforma/applications/guias/ guides_hub: applications --- -Cada guia abre na seção Guias, onde todos os guias ficam. +Este hub lista todos os guias e tutoriais de Applications e de Cache, Application Accelerator e Image Processor, e cada um abre na seção Guias. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/cache-settings.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/cache-settings.mdx index 9fe23768f3..24622fa363 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/cache-settings.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/cache-settings.mdx @@ -1,7 +1,7 @@ --- title: Cache settings description: >- - Consulte todos os campos de um cache setting: TTLs de browser e de cache, + Consulte todos os campos de um cache setting: TTLs de navegador e de cache, stale cache, Tiered Cache, variação de cache, corpo da API, erros e limites. meta_tags: 'cache settings, cache setting, browser cache, max age, stale cache, tiered cache, large file optimization, cache vary by, api v4, azion cli' namespace: documentation_products_edge_application_cache_settings @@ -12,7 +12,9 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Um cache setting é um conjunto de valores que dizem ao [Cache](/pt-br/documentacao/plataforma/applications/cache/) como armazenar e entregar uma resposta. Ele pertence a uma Application. Os seus valores são o tempo de vida (TTL) de browser, o TTL e o comportamento de cache, o stale cache, a Large File Optimization, [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) e as variações de cache. Uma regra do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) com o behavior [Set Cache Policy](/pt-br/documentacao/plataforma/applications/rules-engine/#set-cache-policy) aplica o cache setting, e ele age apenas sobre as requisições às quais essa regra corresponde. Para criar um, consulte [Crie um cache setting](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/ajustar-cache-settings/). +Um cache setting é um conjunto de valores que dizem ao [Cache](/pt-br/documentacao/plataforma/applications/cache/) como armazenar e entregar uma resposta. Ele pertence a uma Application. Os seus valores são o tempo de vida (TTL) de navegador, o TTL e o comportamento de cache, o stale cache, a Large File Optimization, [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) e as variações de cache. + +Uma regra do [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) com o behavior [Set Cache Policy](/pt-br/documentacao/plataforma/applications/rules-engine/#set-cache-policy) aplica o cache setting, e ele age apenas sobre as requisições às quais essa regra corresponde. Para criar um, consulte [Crie um cache setting](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/ajustar-cache-settings/). --- @@ -25,7 +27,7 @@ Seis interfaces criam e alteram o mesmo cache setting. As tabelas desta página | [Azion Console](https://console.azion.com/) | A aba **Cache Settings** de uma Application em [Applications](/pt-br/documentacao/plataforma/applications/) e, em seguida, **+ Cache**, que abre o drawer **Create Cache Settings** | A mesma aba lista cada setting com seu **Name**, **Browser Cache** e **Cache** | | [Azion API v4](/pt-br/documentacao/devtools/api/) | `POST /v4/workspace/applications/{application_id}/cache_settings` | `GET`, `PUT`, `PATCH` e `DELETE /v4/workspace/applications/{application_id}/cache_settings/{cache_setting_id}`; `GET /v4/workspace/applications/{application_id}/cache_settings` lista todos | | Azion CLI | [`azion create cache-setting`](/pt-br/documentacao/devtools/cli/recursos/cache-setting/) | [`azion describe cache-setting`](/pt-br/documentacao/devtools/cli/recursos/cache-setting/), [`azion list cache-setting`](/pt-br/documentacao/devtools/cli/recursos/cache-setting/), [`azion update cache-setting`](/pt-br/documentacao/devtools/cli/recursos/cache-setting/), [`azion delete cache-setting`](/pt-br/documentacao/devtools/cli/recursos/cache-setting/) | -| `azion.config.js` | Uma entrada do array `cache` de uma Application, do tipo `AzionCache` | A mesma entrada | +| [`azion.config.js`](/pt-br/documentacao/devtools/cli/azion-config-js/) | Uma entrada do array `cache` de uma Application, do tipo `AzionCache` | A mesma entrada | | [Azion Lib](/pt-br/documentacao/devtools/azion-lib/application/) | `createCacheSetting`, de `azion/applications` | `getCacheSetting`, `getCacheSettings`, `updateCacheSetting` e `deleteCacheSetting`, de `azion/applications` | | [Terraform](/pt-br/documentacao/devtools/terraform/applications/) | O recurso `azion_application_cache_setting`, cuja página documenta `application_id` e `name` | O mesmo recurso | @@ -35,7 +37,7 @@ No `azion.config.js`, uma entrada `AzionCache` carrega `name`, `stale`, `querySt --- -## General +## Nome No Azion Console, a seção **General** do drawer **Create Cache Settings** carrega o nome. O `name` é o único campo que a API exige. @@ -47,14 +49,14 @@ No Azion Console, a seção **General** do drawer **Create Cache Settings** carr ## Browser Cache -O objeto `browser_cache` define o que o browser é instruído a guardar. No Azion Console, os seus controles ficam na seção **Browser Cache**. +O objeto `browser_cache` define o que o navegador é instruído a guardar. No Azion Console, os seus controles ficam na seção **Browser Cache**. | Controle do Console | Campo da API | Tipo | Valores | Padrão | Flag da CLI | | --- | --- | --- | --- | --- | --- | | Radios de **Browser Cache** | `browser_cache.behavior` | enum | _Honor cache policies_ (`honor`), _Override cache settings_ (`override`), _No cache_ (`no-cache`) | `honor` | `--browser-cache-behavior` | | **Max Age** sob _Override cache settings_ | `browser_cache.max_age` | integer, segundos | 0 a 31.536.000 | `0` | `--browser-cache-max-age` | -`honor` mantém os headers `Cache-Control` e `Expires` enviados pela origem e os repassa ao browser. `override` substitui esses headers pelo TTL em `browser_cache.max_age`. Para `no-cache`, a opção _No cache_ do Azion Console diz: "Disable browser caching to ensure content is always fetched directly from the server". No `azion update cache-setting`, a flag de `browser_cache.behavior` é `--browser-cache-settings`. +`honor` mantém os headers `Cache-Control` e `Expires` enviados pela origem e os repassa ao navegador. `override` substitui esses headers pelo TTL em `browser_cache.max_age`. `no-cache` desativa o cache do navegador. A opção _No cache_ do Azion Console diz: "Disable browser caching to ensure content is always fetched directly from the server". No `azion update cache-setting`, a flag de `browser_cache.behavior` é `--browser-cache-settings`. --- @@ -74,10 +76,16 @@ O objeto `modules.cache` define por quanto tempo a Azion mantém uma cópia de u `honor` mantém os headers `Cache-Control` e `Expires` enviados pela origem, e `override` os substitui pelo TTL em `modules.cache.max_age`. Quando a origem não envia nem `Cache-Control` nem `Expires`, `honor` mantém a cópia pelo Max Age do cache setting, `modules.cache.max_age`. -O stale cache, o campo `stale_cache.enabled`, permite que a Azion entregue uma cópia expirada por uma janela limitada quando a origem não responde. A Large File Optimization, o campo `large_file_cache.enabled`, armazena um objeto grande em fragmentos, e `large_file_cache.offset` carrega o tamanho deles, fixo em 1.024 kB. Tiered Cache é uma feature de Cache que adiciona uma segunda camada de cache entre o data center que responde a uma requisição e a sua origem. O `tiered_cache.enabled` a ativa para os objetos que esse cache setting coloca em cache, e o `tiered_cache.topology` seleciona onde essa camada os mantém. Um objeto `tiered_cache` enviado sem `enabled` ativa a camada. Para saber como cada um se comporta em uma requisição, consulte [Expiração e atualização](/pt-br/documentacao/plataforma/applications/cache/expiracao-e-atualizacao/). +O stale cache, ativado em `stale_cache.enabled`, permite que a Azion entregue uma cópia expirada por uma janela limitada quando a origem não responde. A Large File Optimization, ativada em `large_file_cache.enabled`, armazena um objeto grande em fragmentos, e `large_file_cache.offset` carrega o tamanho deles, fixo em 1.024 kB. + +Tiered Cache é uma feature de Cache que adiciona uma segunda camada de cache entre o data center que responde a uma requisição e a sua origem. O `tiered_cache.enabled` a ativa para os objetos que esse cache setting coloca em cache, e o `tiered_cache.topology` seleciona onde essa camada os mantém. Um objeto `tiered_cache` enviado sem `enabled` ativa a camada. + +Para saber como cada um se comporta em uma requisição, consulte [Expiração e atualização](/pt-br/documentacao/plataforma/applications/cache/expiracao-e-atualizacao/). :::note[nota] -Duas restrições se aplicam a esses valores. Um `modules.cache.max_age` abaixo de 60 segundos exige [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) na Application; sem ele, a API recusa o cache setting com o erro `21021`. No Azion Console, o campo **Max Age** informa um mínimo de 3 segundos assim que **Large file optimization** é ativado. Sem Application Accelerator, a API continua recusando um valor abaixo de 60 segundos com o erro `21021`. Tiered Cache exige `override` em `modules.cache.behavior`; com `honor`, a API recusa o cache setting com o erro `21001`. No Azion Console, ativar **Large file optimization** ou **Tiered Cache** desabilita a opção _Honor cache policies_ e seleciona _Override cache behavior_, mas a API aceita `honor` com a Large File Optimization. +Um `modules.cache.max_age` abaixo de 60 segundos exige [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) na Application, ou a API recusa o cache setting com o erro `21021`. No Azion Console, o campo **Max Age** informa um mínimo de 3 segundos assim que **Large file optimization** é ativado. + +Tiered Cache exige `override` em `modules.cache.behavior`, ou a API recusa o cache setting com o erro `21001`. No Azion Console, ativar **Large file optimization** ou **Tiered Cache** desabilita a opção _Honor cache policies_ e seleciona _Override cache behavior_, mas a API aceita `honor` com a Large File Optimization. ::: --- @@ -90,7 +98,7 @@ Juntos, os campos de `modules.application_accelerator` configuram Advanced Cache | Controle do Console | Campo da API | Tipo | Valores | Padrão | Flag da CLI | | --- | --- | --- | --- | --- | --- | -| **Cache vary by Method** > **POST**, **OPTIONS** | `cache_vary_by_method` | array de enum, no máximo 2 valores | `post`, `options` | `[]` | Na criação, `--enable-caching-for-options` e `--file`. Na atualização, `--enable-caching-for-options` e `--enable-caching-for-post` | +| **Cache vary by Method** > **POST**, **OPTIONS** | `cache_vary_by_method` | array de enum, no máximo 2 valores | `post`, `options` | `[]` | Criação: `--enable-caching-for-options`, `--file`. Atualização: também `--enable-caching-for-post` | | **Cache vary by Query String** > **Behavior** | `cache_vary_by_querystring.behavior` | enum | _Ignore_ (`ignore`), _All_ (`all`), _Allowlist_ (`allowlist`), _Denylist_ (`denylist`) | `ignore` | `--cache-by-query-string` | | **Cache vary by Query String** > **Fields** | `cache_vary_by_querystring.fields` | array de string | nomes de argumentos de query string | `[]` | `--query-string-fields` | | **Cache vary by Query String** > **Sort** | `cache_vary_by_querystring.sort_enabled` | boolean | `true`, `false` | `false` | Na criação, apenas `--file`. Na atualização, `--enable-caching-string-sort` | @@ -101,13 +109,15 @@ Juntos, os campos de `modules.application_accelerator` configuram Advanced Cache No `azion create cache-setting`, a `--enable-caching-for-options` escreve `options` qualquer que seja o seu valor, e `post` exige `--file`. No `azion update cache-setting`, uma chamada que passa uma flag de método remove o outro método, então passe as duas flags para manter os dois. -`ignore` mantém a mesma key, quaisquer que sejam os valores, e `all` varia a key por todos os valores que chegam. `allowlist` varia a key pelos valores nomeados, e `denylist` varia a key por todos os valores exceto os nomeados. `fields`, `cookie_names` e `device_group` carregam os valores nomeados. `sort_enabled` agrupa os mesmos argumentos sob uma key, em qualquer ordem que cheguem. `allowlist` e `denylist` na query string exigem pelo menos um campo, ou a API retorna o erro `21018`. Para os passos no Azion Console que configuram esses controles, consulte [Configure a Advanced Cache Key para uma aplicação](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/advanced-cache-key/). +`ignore` mantém a mesma key, quaisquer que sejam os valores, e `all` varia a key por todos os valores que chegam. `allowlist` varia a key pelos valores nomeados, e `denylist` varia a key por todos os valores exceto os nomeados. `fields`, `cookie_names` e `device_group` carregam os valores nomeados. + +`sort_enabled` agrupa os mesmos argumentos sob uma key, em qualquer ordem que cheguem. `allowlist` e `denylist` na query string exigem pelo menos um campo, ou a API retorna o erro `21018`. Para os passos no Azion Console que configuram esses controles, consulte [Configure a Advanced Cache Key para uma aplicação](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/advanced-cache-key/). --- ## Corpo da requisição e comando da CLI -O corpo abaixo cria um cache setting completo pelo `POST /v4/workspace/applications/{application_id}/cache_settings`: +O corpo abaixo cria um cache setting completo pelo `POST /v4/workspace/applications/{application_id}/cache_settings`. Ele mantém cada resposta por 300 segundos no cache da Azion e por um dia no navegador: ```json { @@ -128,20 +138,36 @@ O corpo abaixo cria um cache setting completo pelo `POST /v4/workspace/applicati A API responde com HTTP `201`, `state` igual a `executed` e o novo cache setting com o seu `id` em `data`: ```json -{"state":"executed","data":{"id":123456,"name":"static-assets",...,"created_at":"2026-01-01T12:00:00.577248Z"}} +{ + "state": "executed", + "data": { + "id": 123456, + "name": "static-assets", + ..., + "created_at": "2026-01-01T12:00:00.577248Z" + } +} ``` O endpoint de listagem envolve os cache settings de uma Application em um envelope de página: ```json -{"count":2,"total_pages":1,"page":1,"page_size":10,"next":null,"previous":null,"results":[...]} +{ + "count": 2, + "total_pages": 1, + "page": 1, + "page_size": 10, + "next": null, + "previous": null, + "results": [...] +} ``` A CLI escreve pela linha de comando os campos cobertos por suas flags: ```bash azion create cache-setting \ - --application-id \ + --application-id \ --name "product-listing" \ --browser-cache-behavior override \ --browser-cache-max-age 30 \ @@ -157,7 +183,7 @@ O comando imprime o id do novo cache setting: Created Cache Settings configuration with ID 123457 ``` -No `azion create cache-setting`, as flags cobrem o browser cache, a variação por query string e por cookie e o cache de `OPTIONS`, e o `azion update cache-setting` também define `sort_enabled` e o cache de `POST`. Cada um dos outros campos é definido pelo `--file` com o corpo JSON: `modules.cache.max_age`, o comportamento de cache, o stale cache, a Large File Optimization e Tiered Cache. +No `azion create cache-setting`, as flags cobrem o cache do navegador, a variação por query string e por cookie e o cache de `OPTIONS`, e o `azion update cache-setting` também define `sort_enabled` e o cache de `POST`. Cada um dos outros campos é definido pelo `--file` com o corpo JSON: `modules.cache.max_age`, o comportamento de cache, o stale cache, a Large File Optimization e Tiered Cache. --- diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/device-groups.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/device-groups.mdx index b2195dfc35..ea632df1be 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/device-groups.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/device-groups.mdx @@ -10,13 +10,15 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Device Groups é uma feature de Applications que agrupa as requisições recebidas por uma [Application](/pt-br/documentacao/plataforma/applications/) de acordo com o dispositivo do cliente. Um device group é um nome e uma expressão regular que a Application compara com o header `User-Agent` de cada requisição. Uma requisição pertence ao grupo quando o header dela corresponde à expressão. Os device groups exigem [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) ativado na Application. Uma [regra](/pt-br/documentacao/plataforma/applications/rules-engine/) ou um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) pode, então, tratar esses dispositivos de forma separada do restante. Cada Application tem os seus próprios device groups, e [Crie device groups](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/criar-device-groups/) mostra como adicionar um no Azion Console. +Device Groups é uma feature de Applications que agrupa as requisições recebidas por uma [Application](/pt-br/documentacao/plataforma/applications/) de acordo com o dispositivo do cliente. Um device group é um nome e uma expressão regular que a Application compara com o header `User-Agent` de cada requisição. Uma requisição pertence ao grupo quando o header dela corresponde à expressão. + +Os device groups exigem [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) ativado na Application. Uma [regra](/pt-br/documentacao/plataforma/applications/rules-engine/) ou um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) pode, então, tratar esses dispositivos de forma separada do restante. Cada Application tem os seus próprios device groups, e [Crie device groups](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/criar-device-groups/) mostra como adicionar um no Azion Console. --- ## Campos do device group -Um device group carrega dois campos que você define, e um ID e uma data de criação que a plataforma atribui. Uma regra se refere a um device group pelo nome, e um cache setting se refere a ele pelo ID. Para os dois campos que você define, a coluna Campo traz o rótulo que o Azion Console mostra. +Um device group carrega dois campos que você define, e um ID e uma data de criação que a plataforma atribui. Uma regra se refere a um device group pelo nome, e um cache setting se refere a ele pelo ID. Para os dois campos que você define, a coluna Campo traz o rótulo que Azion Console mostra. | Campo | Campo da API | Tipo | Limites na API | Descrição | | --- | --- | --- | --- | --- | @@ -25,7 +27,7 @@ Um device group carrega dois campos que você define, e um ID e uma data de cria | ID | `id` | integer | Somente leitura | O identificador do grupo | | Data de criação | `created_at` | date-time | Somente leitura | Quando o grupo foi criado | -A cache key de uma cópia que varia por dispositivo termina com o nome do grupo. O nome aceita somente letras e números, sem espaços nem símbolos, e a API recusa outro nome com HTTP `400` e o erro `27003`, `Device Group Invalid Name`. No Azion Console, o campo **Name** informa `Use only letters and numbers, without spaces or symbols.` Azion Console mostra `Name must be alphanumeric` para um nome com outros caracteres. +A cache key de uma cópia em cache de um objeto que varia por dispositivo termina com o nome do grupo. O nome aceita somente letras e números, sem espaços nem símbolos, e a API recusa outro nome com HTTP `400` e o erro `27003`, `Device Group Invalid Name`. No Azion Console, o campo **Name** informa `Use only letters and numbers, without spaces or symbols.` Azion Console mostra `Name must be alphanumeric` para um nome com outros caracteres. A expressão regular segue as Perl Compatible Regular Expressions (PCRE). Azion Console mostra estas mensagens para uma expressão que ele recusa: @@ -33,8 +35,6 @@ A expressão regular segue as Perl Compatible Regular Expressions (PCRE). Azion - `User Agent cannot contain emojis or null bytes` para uma expressão que carrega um dos dois. - `User Agent cannot contain < > " or '` para uma expressão que carrega um desses caracteres. -O campo `cache_vary_by_devices.device_group` de um cache setting lista os device groups pelo ID. - --- ## Header User-Agent @@ -67,7 +67,7 @@ Uma Application compara a expressão regular de cada device group com o header ` ### Ordem de correspondência -Quando um header `User-Agent` corresponde a mais de um device group, a requisição recebe o primeiro grupo que corresponde, do primeiro ao último na lista de device groups. A posição das palavras que correspondem dentro do header não muda o resultado. Por exemplo, uma Application tem estes três device groups, nesta ordem: +Quando um header `User-Agent` corresponde a mais de um device group, a requisição recebe a primeira correspondência na lista de device groups. A posição das palavras que correspondem dentro do header não muda o resultado. Por exemplo, uma Application tem estes três device groups, nesta ordem: | Ordem | Device group | Expressão regular | | --- | --- | --- | @@ -101,11 +101,17 @@ Para todas as variáveis e todos os operadores que uma regra pode usar, consulte ## Variação de cache -Um cache setting pode variar a cache key por device group. Com a variação, [Cache](/pt-br/documentacao/plataforma/applications/cache/) armazena uma cópia separada de um objeto para cada device group que o cache setting lista. Caso contrário, Cache responde a todos os dispositivos com a mesma cópia. Na API, a variação é o campo `modules.application_accelerator.cache_vary_by_devices`, cujo campo `device_group` lista os device groups por ID. Um cache setting que não define a variação carrega `"behavior": "ignore"` e uma lista `device_group` vazia. [Azion CLI](/pt-br/documentacao/devtools/cli/) não tem flag para a variação por device group. +Um cache setting pode variar a cache key por device group. Com a variação, [Cache](/pt-br/documentacao/plataforma/applications/cache/) armazena uma cópia separada de um objeto para cada device group que o cache setting lista. Caso contrário, Cache responde a todos os dispositivos com a mesma cópia. + +Na API, a variação é o campo `modules.application_accelerator.cache_vary_by_devices`, cujo campo `device_group` lista os device groups por ID. Um cache setting que não define a variação carrega `"behavior": "ignore"` e uma lista `device_group` vazia. [Azion CLI](/pt-br/documentacao/devtools/cli/) não tem flag para a variação por device group. O objeto `modules.application_accelerator` de um cache setting exige Application Accelerator ativado na Application. Sem ele, a API recusa com o erro `21013` uma variação desse objeto cujo `behavior` não é `ignore`. Para os valores que cada campo aceita e o rótulo dele no Azion Console, consulte [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/#cache-variation). -Cada cópia que varia por device group tem a sua própria cache key. A key termina em `@@` e no nome do device group, como `httpwww.example.com/@@Mobile`. Um purge por URL não alcança essas cópias, então purgue-as por cache key ou com um wildcard. Para o formato da key, consulte [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#variacoes). Para os tipos de purge, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purge-por-url). +Cada cópia que varia por device group tem a sua própria cache key. A key termina em `@@` e no nome do device group, como `httpwww.example.com/@@Mobile`. Para o formato da key, consulte [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/#variacoes). Para os tipos de purge, consulte [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/#purge-por-url). + +:::caution[Atenção] +Um purge por URL não alcança as cópias que variam por device group, então purgue-as por cache key ou com um wildcard. +::: --- @@ -142,6 +148,18 @@ Azion CLI gerencia device groups com cinco comandos sob o substantivo `device-gr --- +## Erros + +A API recusa um device group, ou um cache setting que varia por um deles, com estes erros: + +| Código | Título | Status | O que causa | O que fazer | +| --- | --- | --- | --- | --- | +| `27002` | `Application Acceleration Not Enabled` | 403 | Um device group novo, com Application Accelerator desativado | Ative Application Accelerator e, em seguida, crie o device group novamente | +| `27003` | `Device Group Invalid Name` | 400 | Um `name` com caracteres que não são letras ou números | Use somente letras e números | +| `21013` | `This Configuration Requires The Edge Application's Application Accelerator Module` | 400 | Uma variação por device group em um cache setting, com Application Accelerator desativado | Ative Application Accelerator e, em seguida, salve o cache setting novamente | + +--- + ## Recursos relacionados diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/domains/mtls.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/domains/mtls.mdx index 30d4474954..f632dfb9bf 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/domains/mtls.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/domains/mtls.mdx @@ -105,7 +105,7 @@ Um Workload verifica certificados de cliente somente quando estas condições s - **Existe um certificado de CA confiável no Certificate Manager.** Uma autoridade certificadora de terceiros o emite, e você o envia antes de definir `mtls.config.certificate`. Um certificado que a Azion gera, como o certificado SAN da Azion, não pode servir como CA confiável. - **Os clientes enviam SNI no modo `enforce`.** Server Name Indication (SNI) é a extensão TLS que indica o host no handshake. Uma conexão sem SNI chega à configuração padrão, que apresenta o certificado SAN da Azion. Esse certificado é da própria Azion, com os hostnames dele listados como Subject Alternative Names (SAN). Em um Workload no modo `enforce`, a Azion fecha essa conexão antes de resolver uma rota da sua aplicação. -Para o tamanho máximo de um certificado de CA confiável, consulte [Limites de Workloads](/pt-br/documentacao/plataforma/workloads/limites/). +Para o tamanho máximo de um certificado de CA confiável, consulte [Limites de Certificate Manager](/pt-br/documentacao/plataforma/certificate-manager/limites/). --- @@ -147,6 +147,6 @@ O Workload solicita um certificado, o cliente não envia nenhum e a conexão ter Os certificados de CA confiável que um Workload usa no mTLS, as CRLs que ele lista e como enviar cada um. Os passos que enviam uma CA confiável, ativam o mTLS em um Workload e adicionam uma regra permissive. Todos os outros campos de um Workload, de domínios e portas ao certificado de servidor em TLS. - O limite do tamanho de um certificado de CA confiável. + O limite do tamanho de um certificado de CA confiável. diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-app-primeiros-passos.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-app-primeiros-passos.mdx index 379156f07c..0db8a441cd 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-app-primeiros-passos.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-app-primeiros-passos.mdx @@ -22,15 +22,17 @@ Este guia orienta você a entregar o conteúdo da sua origem pela sua primeira [ Cinco partes formam a cadeia, listadas na ordem em que este guia as usa: -1. O **Connector** guarda o endereço da sua origem e a forma como a Azion se conecta a ela. -2. A **Application** guarda as regras que decidem o que acontece com uma requisição. Uma Application nova não tem regras. -3. A **regra** na Application combina uma condição sobre a requisição, chamada critério, com uma ação chamada behavior. Neste guia, o critério corresponde a toda requisição, e o behavior _Set Connector_ envia a requisição para o Connector. -4. O **Workload** guarda um domínio e recebe as requisições enviadas a ele. O **deployment** dele, uma configuração do Workload, define a Application que recebe essas requisições. +1. O **Connector** guarda o endereço da sua origem e as configurações que a Azion usa para alcançá-la. +2. A **Application** processa as requisições que o Workload recebe, e as regras dela decidem o que acontece com cada requisição. Uma Application nova não tem regras. +3. A **regra** é uma entrada no Rules Engine para Applications que executa os seus behaviors, em uma fase, sobre as requisições às quais os seus critérios correspondem. Um critério é uma condição sobre a requisição, e um behavior é a ação que a regra executa. Neste guia, o critério corresponde a toda requisição, e o behavior _Set Connector_ envia a requisição para o Connector. +4. O **Workload** guarda um domínio e recebe as requisições enviadas a ele. O **deployment** dele é a parte do Workload que define a Application que recebe essas requisições. 5. A **requisição** vai para o domínio de workload, o hostname que a Azion atribui ao Workload. A regra da Application corresponde à requisição, e o Connector a encaminha para a sua origem. Um Connector só recebe requisições depois que uma regra define esse Connector. Uma Application só recebe as requisições de um Workload depois que o deployment desse Workload define essa Application. -Cada Application tem quatro interruptores: [Cache](/pt-br/documentacao/plataforma/applications/cache/), [Functions](/pt-br/documentacao/plataforma/functions/), [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) e [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/). No Azion Console, os interruptores ficam em **Main Settings** > **Modules**, e na API, eles são as chaves de `modules`. Uma Application nova começa com Cache e Functions ativados e os outros dois desativados, e este guia mantém os quatro como estão. Os primeiros passos de Cache, Application Accelerator e Image Processor começam onde este guia termina, com uma Application que já entrega conteúdo. +Cada Application tem quatro switches: [Cache](/pt-br/documentacao/plataforma/applications/cache/), [Functions](/pt-br/documentacao/plataforma/functions/), [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) e [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/). No Azion Console, os switches ficam em **Main Settings** > **Modules**, e na API, eles são as chaves de `modules`. Uma Application nova começa com Cache e Functions ativados e os outros dois desativados, e este guia mantém os quatro como estão. + +Os primeiros passos de Cache, Application Accelerator e Image Processor começam onde este guia termina, com uma Application que já entrega conteúdo. --- @@ -248,7 +250,7 @@ O Connector está ativo, e o endereço dele aceita conexões HTTPS na `https_por ## Crie a Application -Uma Application guarda as regras que decidem o que acontece com cada requisição. Ela precisa apenas de um nome, e todas as outras configurações mantêm o valor padrão. A Application só alcança a sua origem por uma regra que define um Connector. +Uma Application processa as requisições recebidas por um Workload, e as regras dela decidem o que acontece com cada requisição. Ela precisa apenas de um nome, e todas as outras configurações mantêm o valor padrão. A Application só alcança a sua origem por uma regra que define um Connector. @@ -312,7 +314,7 @@ Para criar a Application pela API, envie uma requisição `POST` para o endpoint --header 'Content-Type: application/json' \\ --data '{"name": "first-application", "active": true}'`} /> -Na resposta, `modules` lista os interruptores com que a Application começa: +Na resposta, `modules` lista os switches com que a Application começa: ```json { @@ -346,7 +348,9 @@ A Application está ativa e não tem regras. Em `modules`, `cache` e `functions` ## Envie toda requisição para o Connector -Uma regra no [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) combina critérios com behaviors. Esta regra roda na Request Phase. O critério dela, `${uri}` começando com `/`, corresponde a toda requisição. O behavior dela, _Set Connector_, envia cada requisição correspondente para o seu Connector. Para mais informações, consulte [Set Connector](/pt-br/documentacao/plataforma/applications/rules-engine/#set-connector). +Uma regra no [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) executa os seus behaviors, em uma fase, sobre as requisições às quais os seus critérios correspondem. Esta regra roda na Request Phase, e o critério dela, `${uri}` começando com `/`, corresponde a toda requisição. + +O behavior desta regra, _Set Connector_, envia cada requisição correspondente para o seu Connector. Para mais informações, consulte [Set Connector](/pt-br/documentacao/plataforma/applications/rules-engine/#set-connector). O critério usa `${uri}`, não `${request_uri}`. `${request_uri}` precisa de Application Accelerator ativado. Em uma Application com Application Accelerator desativado, a API recusa a regra com `400` e o erro `25047`, `Missing Required Modules`. @@ -521,7 +525,7 @@ A resposta traz a regra armazenada. Este trecho mantém o `id`, o critério, o b ## Entregue a Application por um Workload -Um Workload recebe as requisições enviadas aos domínios dele. Ele guarda esses domínios, os protocolos e os certificados, então você configura a entrega no Workload, não na Application. O deployment do Workload define a Application que recebe essas requisições, e um Workload tem um único deployment. Um Workload novo responde em um domínio de workload que a Azion atribui sob `map.azionedge.net`. +Um Workload recebe as requisições enviadas aos domínios dele. Ele guarda esses domínios, os protocolos e os certificados, então você configura a entrega no Workload, não na Application. O deployment do Workload define a Application que recebe essas requisições, e um Workload tem no máximo um deployment. Um Workload novo responde em um domínio de workload que a Azion atribui sob `map.azionedge.net`. @@ -595,7 +599,7 @@ ID CURRENT EDGE APPLICATION EDGE FIREWALL true 0 ``` -O deployment do Workload define a sua Application. Um projeto que declara o Workload no `azion.config.js` recebe o deployment do `azion deploy` no lugar desse comando, e esse deployment define a Application que o deploy cria para o projeto, mesmo quando a entrada [`deployments`](/pt-br/documentacao/devtools/cli/azion-config-js/#deployments-do-workload) nomeia outra Application pelo ID dela. +O deployment do Workload define a sua Application. Um projeto que declara o Workload no `azion.config.js` recebe o deployment do `azion deploy` no lugar desse comando. Esse deployment define a Application que o deploy cria para o projeto, mesmo quando a entrada [`deployments`](/pt-br/documentacao/devtools/cli/azion-config-js/#deployments-do-workload) nomeia outra Application pelo ID dela. Para encontrar o domínio de workload, descreva o Workload em JSON: @@ -619,7 +623,9 @@ Na saída, o campo `workload_domain` guarda o domínio para onde vai a requisiç ### API -Para criar o Workload pela API, envie uma requisição `POST` para o endpoint de workloads. `infrastructure` definido como `1` seleciona a infraestrutura de produção, e `workload_domain_allow_access` definido como `true` deixa o Workload responder no domínio de workload dele. Substitua `[TOKEN VALUE]` pelo seu personal token: +Para criar o Workload pela API, envie uma requisição `POST` para o endpoint de workloads. + +`infrastructure` definido como `1` seleciona a infraestrutura de produção, e `workload_domain_allow_access` definido como `true` deixa o Workload responder no domínio de workload dele. Substitua `[TOKEN VALUE]` pelo seu personal token: ` pelo `id` do Workload e `` pelo ID da sua Application: + + --name first-deployment --application-id `} /> + +O comando imprime o ID do deployment novo: + +```text +Created Workload Deployment with ID +``` + +O deployment do Workload define a sua Application. @@ -680,7 +696,9 @@ Para definir a sua Application no deployment do Workload que você criou, execut Esta etapa precisa apenas do `curl`, qualquer que seja a interface que você usou para montar a cadeia. No comando, substitua `` pelo domínio de workload do Workload que você criou. -Um Workload novo só retorna a resposta da sua origem depois que o primeiro deployment dele chega ao tráfego. Isso pode levar vários minutos, e a Azion não garante nenhuma duração. Até lá, o domínio de workload responde `404` com uma página provisória. Enquanto o deployment se propaga, as respostas à mesma requisição podem alternar entre esse `404` e a resposta da sua origem. Repita a requisição até a resposta vir da sua origem. Para mais informações, consulte [Propagação](/pt-br/documentacao/plataforma/applications/como-funciona/#propagacao). +Um Workload novo só retorna a resposta da sua origem depois que o primeiro deployment dele chega ao tráfego. Isso pode levar vários minutos, e a Azion não garante nenhuma duração. Até lá, o domínio de workload responde `404` com uma página provisória. + +Enquanto o deployment se propaga, as respostas à mesma requisição podem alternar entre esse `404` e a resposta da sua origem. Repita a requisição até a resposta vir da sua origem. Para mais informações, consulte [Propagação](/pt-br/documentacao/plataforma/applications/como-funciona/#propagacao). Envie uma requisição para o caminho raiz do seu domínio de workload: diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-application.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-application.mdx index c68847d545..d0a60e3150 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-application.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-application.mdx @@ -13,20 +13,28 @@ import VersionRollingOut from '~/includes/snippets/versionRollingOut/pt/snippet. [Applications | v3](/pt-br/documentacao/plataforma/applications/v3/) -**Applications** é um recurso da plataforma que processa as requisições recebidas pelos seus [Workloads](/pt-br/documentacao/plataforma/workloads/). Uma Application pode executar funções serverless, atuar como proxy reverso para as suas origens ou combinar os dois, na infraestrutura distribuída da Azion, a partir do data center mais próximo ao seu usuário. Uma função serverless é uma [Function](/pt-br/documentacao/plataforma/functions/), um código executado sob demanda a cada requisição, sem um servidor para você provisionar. Um proxy reverso é um servidor na frente da sua origem, o servidor que guarda o seu conteúdo. O proxy pode responder a cada requisição com uma cópia em cache de uma resposta anterior da origem, adicionar ou remover headers ou encaminhar a requisição à sua origem. Toda requisição passa pelo proxy, então os seus clientes acessam um único domínio, e o proxy aplica a lógica que cada origem teria de repetir. +**Applications** é um recurso da plataforma que processa as requisições recebidas pelos seus [Workloads](/pt-br/documentacao/plataforma/workloads/), a partir do data center mais próximo ao seu usuário. Uma Application pode executar funções serverless, atuar como proxy reverso para as suas origens ou combinar os dois. Ela também pode armazenar respostas com [Cache](/pt-br/documentacao/plataforma/applications/cache/), liberar quatro capacidades para o cache e as regras com [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) e transformar imagens com [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/). Use Applications para executar uma [Function](/pt-br/documentacao/plataforma/functions/), definir o [Connector](/pt-br/documentacao/plataforma/connectors/) que chega a cada origem, adicionar ou remover headers ou reescrever requisições. -Uma Application recebe as requisições de um Workload depois que o deployment desse Workload define essa Application. Em cada requisição, a Application executa as suas regras. Uma regra pode definir o [Connector](/pt-br/documentacao/plataforma/connectors/) que encaminha a requisição à sua origem, decidir se a resposta é armazenada em cache ou executar uma Function. Use Applications para encaminhar cada path à sua origem, armazenar respostas em cache, adicionar ou remover headers, reescrever requisições, executar o seu próprio código nas requisições a que uma regra corresponde ou redimensionar e converter imagens sob demanda. +Cada Application pode usar estes recursos aninhados e features: + +- [Cache](/pt-br/documentacao/plataforma/applications/cache/) permite que uma Application responda a uma requisição com uma cópia de uma resposta anterior da origem. Por exemplo, os seus arquivos estáticos ficam no data center mais próximo ao seu usuário. +- [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) é a escolha certa quando uma URL tem mais de uma resposta correta, como uma página personalizada ou a resposta a um `POST`. Cache então guarda uma cópia separada por valor de argumento de query string, cookie, device group ou método. +- [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) atende a uma página que precisa de uma imagem em vários tamanhos, recortes, qualidades ou formatos, como WEBP para navegadores que o aceitam. Cada variante sai de um arquivo único na origem, o único que você armazena e envia. +- [Device Groups](/pt-br/documentacao/plataforma/applications/device-groups/) permite que uma Application diferencie os dispositivos que enviam as suas requisições, para que uma regra ou um cache setting trate cada grupo de forma diferente. Ele precisa de Application Accelerator ativo na Application. +- [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/) é onde você escreve o que uma Application faz com cada requisição que recebe. Por exemplo, uma regra pode encaminhar `/api/` para uma origem enquanto uma segunda regra encaminha todos os outros paths para outra. +- [WebSocket Proxy](/pt-br/documentacao/plataforma/applications/websocket/) permite que uma Application transporte uma conexão WebSocket entre os seus usuários e a sua origem. A Azion o ativa em uma conta somente mediante solicitação. +- Uma [Function Instance](/pt-br/documentacao/plataforma/applications/functions-instances/) permite que uma Application execute uma das suas Functions. Por exemplo, a mesma Function pode ser executada em mais de uma Application, cada Function Instance com os seus próprios argumentos. - + --- ## Caminho da requisição -Criar uma Application não encaminha nenhuma requisição a ela: antes, o deployment de um Workload precisa definir essa Application. Uma Application também só chega a uma origem por meio de uma regra que define um Connector. O diagrama acompanha uma requisição que segue esse caminho. No lugar de uma origem, uma Function pode responder a uma requisição: uma regra executa a Function com _Run Function_, e a Function constrói a resposta sem nenhum Connector. +Criar uma Application não lhe encaminha requisições: elas só chegam a ela depois que o deployment de um Workload define essa Application. A Application então só chega a uma origem por meio de uma regra que define um Connector. No lugar de uma origem, uma regra pode executar uma Function que constrói a resposta sem nenhum Connector. -As setas sólidas levam a requisição, e as setas pontilhadas levam a resposta. Cada rótulo começa com o número do seu passo abaixo. +O diagrama acompanha uma requisição que chega a uma origem. As setas sólidas levam a requisição, e as setas pontilhadas levam a resposta. Cada rótulo começa com o número do seu passo abaixo. ```mermaid %%{init: {"layout": "elk", "elk": {"cycleBreakingStrategy": "MODEL_ORDER"}, "themeVariables": {"fontSize": "13px"}, "flowchart": {"nodeSpacing": 24, "rankSpacing": 36, "padding": 8, "wrappingWidth": 150, "useMaxWidth": true}, "sequence": {"width": 120, "actorMargin": 30, "useMaxWidth": true}}}%% @@ -53,104 +61,11 @@ flowchart TD App -.->|"5. resposta"| Client ``` -1. A requisição chega a um Workload por um dos domínios dele, e o deployment do Workload define a Application. No Azion Console, você define essa Application no campo **Application** de **Deployment Settings**. Um [Firewall](/pt-br/documentacao/plataforma/firewall/) que o deployment também define executa as suas regras primeiro e pode interromper a requisição ali. -2. As regras da Request Phase da Application são executadas em ordem. Quando um behavior, a ação que uma regra executa, encerra o processamento, como faz _Deny (403 Forbidden)_, a Application responde ao cliente e nenhuma regra posterior é executada. -3. Se uma regra com o behavior _Set Cache Policy_ aplicou um cache setting, [Cache](/pt-br/documentacao/plataforma/applications/cache/) procura uma cópia válida da resposta da origem. Quando Cache tem uma, essa cópia se torna a resposta, e a origem não recebe nenhuma requisição. -4. Caso contrário, o Connector definido por uma regra com _Set Connector_ encaminha a requisição à origem. Se várias regras que correspondem à requisição carregam _Set Connector_, somente a última delas é executada. -5. Depois, as regras da Response Phase da Application são executadas sobre a resposta, e a resposta chega ao cliente. - -Uma Application nova começa com Cache e [Functions](/pt-br/documentacao/plataforma/functions/) ativos, Application Accelerator e [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) desativados e nenhuma regra. - -Uma alteração não vale de imediato: ela se propaga, e a Azion não garante nenhum tempo de propagação. Até que o deployment de um Workload novo se propague, o que pode levar vários minutos, o Workload responde com o `404` de placeholder da Azion. Nesse intervalo, as respostas se alternam entre o placeholder e a resposta da Application, então repita a requisição até que elas concordem. Para o funcionamento das duas fases, a ordem das regras e dos behaviors e a propagação, consulte [Como Applications funciona](/pt-br/documentacao/plataforma/applications/como-funciona/). - ---- - -## Estrutura da regra - -Uma regra é a unidade de lógica de uma Application. Os critérios dela testam cada requisição, e os behaviors dela são executados sobre uma requisição que corresponde a eles. Para encaminhar toda requisição ao Connector que alcança a sua origem, envie esta regra como corpo de `POST /v4/workspace/applications//request_rules`: - -```json -{ - "name": "send-to-origin", - "active": true, - "criteria": [ - [ - { - "variable": "${uri}", - "conditional": "if", - "operator": "starts_with", - "argument": "/" - } - ] - ], - "behaviors": [ - { - "type": "set_connector", - "attributes": { "value": } - } - ] -} -``` - -- `criteria` guarda grupos de condições, e cada grupo começa com uma condição cujo `conditional` é `if`. Aqui, `${uri}` é a URI sem a query string. Todo path começa com `/`, então `starts_with` e `/` correspondem a toda requisição. Se a regra testar `${request_uri}`, que mantém a query string, no lugar de `${uri}`, a API a recusa com `400` e o erro `25047` enquanto [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) está desativado. -- `behaviors` lista as ações que a regra executa sobre uma requisição que corresponde a ela. `set_connector` encaminha a requisição ao Connector cujo ID está em `attributes.value`. Esse Connector guarda o endereço da sua origem. -- `name` e `active` pertencem à própria regra. -- Você também pode montar a mesma regra no Azion Console, como mostra [Primeiros passos com Applications](/pt-br/documentacao/plataforma/applications/primeiros-passos/). - -Quando você envia a regra, a API responde `202` e a retorna com `order` igual a `0`. Esse valor é a posição da regra entre as regras da Request Phase da Application. - -O modelo corresponde ao roteamento por path em um proxy reverso: cada critério é uma condição de correspondência, cada behavior é uma ação e um Connector guarda o endereço do servidor de backend. - ---- - -## Recursos - -Cache, Application Accelerator e Image Processor agem sobre as requisições de uma Application. Cada Application ativa Application Accelerator e Image Processor separadamente, e [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#recursos-da-plataforma) mostra onde, no Azion Console e na API. - -### Cache - -Cache é um recurso da plataforma que armazena cópias das respostas às requisições recebidas por uma Application. Cada cópia fica no data center que a armazenou, e as requisições seguintes pelo mesmo objeto recebem essa cópia até que o tempo de vida (TTL) dela termine. Cache está sempre ativo em uma Application. Ele começa a armazenar cópias quando uma regra com _Set Cache Policy_ aplica um cache setting, que guarda os TTLs. Use Cache para: - -- Manter arquivos estáticos no data center mais próximo ao seu usuário -- Entregar arquivos de vídeo grandes em fragmentos, com a Large File Optimization ativada no cache setting -- Responder às requisições com uma cópia expirada quando a origem não responde, com o stale cache ativado no cache setting -- Remover uma cópia quando a origem muda, com [Real-Time Purge](/pt-br/documentacao/plataforma/applications/cache/real-time-purge/) - -A [visão geral do Cache](/pt-br/documentacao/plataforma/applications/cache/) explica o que um cache setting guarda, como uma requisição chega a uma cópia armazenada e por onde começar. - -### Application Accelerator - -Application Accelerator é um recurso da plataforma que libera quatro capacidades para o cache e para as regras de uma Application: a variação de cache, o cache de respostas `POST` e `OPTIONS`, um Max Age menor que 60 segundos e mais behaviors e variáveis do Rules Engine. Com a variação de cache, um cache setting diferencia duas requisições para a mesma URL por um argumento de query string, um cookie, o device group ou o método da requisição, e Cache mantém uma cópia separada para cada valor. Application Accelerator começa desativado em uma Application nova. Ative-o quando uma URL tem mais de uma resposta correta, por exemplo: - -- Uma página personalizada -- Uma resposta de API que muda com a sua query string -- Um catálogo que difere por dispositivo -- Uma resposta a um `POST` - -A [visão geral do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) explica o que uma variação acrescenta à cache key, o que ativá-lo libera e por onde começar. - -### Image Processor - -Image Processor é um recurso da plataforma que constrói uma imagem nova, a imagem derivada, a partir de uma imagem na sua origem. A query string `ims` da requisição descreve a imagem derivada, como `?ims=fit-in/400x400`, e, mesmo sem a query string `ims`, Image Processor pode converter uma imagem para um formato que o navegador aceita. Ele retorna a imagem derivada sem salvá-la como um ativo da conta. Ele começa desativado em uma Application nova e, mesmo ativo, Image Processor processa somente as requisições às quais uma regra da Request Phase com _Optimize Images_ corresponde. Ative-o quando as suas páginas precisam de uma imagem em vários tamanhos, recortes, qualidades ou formatos, como WEBP para os browsers que o aceitam. Todas as variantes saem, então, de um único arquivo na sua origem, e você armazena e faz upload só desse arquivo. - -A [visão geral do Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) explica como uma requisição se torna uma imagem derivada, o que `ims` aceita e por onde começar. - ---- - -## Escopo e limites - -- **Fases**: toda regra pertence a uma de duas fases. A Request Phase age sobre a requisição antes que exista uma resposta, e a Response Phase age sobre a resposta que o usuário recebe. Você escolhe a fase quando cria a regra e não pode mudá-la depois. Somente as regras da Request Phase podem escolher a origem e o cache setting. [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/#fases) lista as variáveis e os behaviors de cada fase e o recurso da plataforma de que cada um precisa. -- **Origens**: uma Application chega a cada origem por meio de um Connector, então duas regras com dois Connectors podem encaminhar `/api/` para um servidor e todos os outros paths para outro. A origem por trás de um Connector pode ser um servidor web na sua infraestrutura, um serviço em cloud ou um bucket do [Object Storage](/pt-br/documentacao/plataforma/object-storage/). [Use um bucket como origem de uma aplicação](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/dados/bucket-como-connector/) mostra o caso do bucket. Com [Load Balancer](/pt-br/documentacao/plataforma/connectors/load-balancer/) ativado, um Connector do tipo `http` pode distribuir o tráfego entre várias origens. Os Connectors substituem as origens que as versões anteriores de Applications configuravam na Application. -- **Functions**: uma [Function Instance](/pt-br/documentacao/plataforma/applications/functions-instances/) vincula uma das suas [Functions](/pt-br/documentacao/plataforma/functions/) à Application, com os seus próprios argumentos. Uma Function Instance pertence a uma Application, e ela só é executada quando uma regra com _Run Function_ invoca essa Function Instance. Functions começa ativo em uma Application nova, no campo `modules.functions.enabled` dela na API. Somente Functions escritas em Lua são executadas na Response Phase, como informa o formulário da Function Instance no Azion Console: `Only Lua functions can be used in the Response phase.` Para os passos de adicionar a sua primeira Function, consulte [Instancie uma função em uma aplicação](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/instanciar-functions/). -- **Cache e imagens em código**: o código que lê ou grava entradas em cache é executado em uma Function e usa a [Cache API](/pt-br/documentacao/devtools/runtime/api-reference/cache/), porque o próprio Cache não pode executar código. Uma Function que processa imagens por conta própria usa a biblioteca WASM Image Processor, que é separada do recurso da plataforma Image Processor. [Onde Image Processor para](/pt-br/documentacao/plataforma/applications/image-processor/entrega-de-imagens/#onde-image-processor-para) explica a diferença. -- **Dispositivos**: um [device group](/pt-br/documentacao/plataforma/applications/device-groups/) é um nome e uma expressão regular que a Application compara com o header `User-Agent` de cada requisição. Os dois usos de um grupo precisam de Application Accelerator ativo: uma regra testa o grupo por meio de `${device_group}`, e um cache setting pode manter uma cópia por grupo. [Boas práticas de Applications](/pt-br/documentacao/plataforma/applications/boas-praticas/#defina-um-device-group-pelas-palavras-que-so-esse-dispositivo-envia) mostra como escrever uma expressão que corresponda somente aos dispositivos que você pretende alcançar. -- **WebSocket**: [WebSocket Proxy](/pt-br/documentacao/plataforma/applications/websocket/) é uma feature de Applications que transporta uma conexão WebSocket entre os seus usuários e a origem. A conexão abre com os headers `Upgrade: websocket` e `Connection: upgrade`. A Azion ativa a feature em uma conta somente mediante solicitação, e [Diretrizes de suporte](/pt-br/documentacao/suporte/) explica como pedir. Como a Azion recicla as conexões keepalive aproximadamente a cada 15 minutos, o cliente precisa reabrir uma conexão WebSocket quando ela se fecha. -- **Workloads**: um Workload guarda os domínios, os protocolos e os certificados que servem a Application, então você configura a entrega no Workload, não na Application. [Teste uma aplicação pelo arquivo hosts](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/testar-edge-application-atraves-do-arquivo-hosts/) mostra como requisitar uma Application no seu próprio domínio a partir de um dispositivo antes de alterar os registros DNS dele. _Redirect HTTP to HTTPS_ só funciona quando o Workload tem HTTPS. Quando o Connector recebe uma resposta 4xx ou 5xx da sua origem, [Custom Pages](/pt-br/documentacao/plataforma/custom-pages/) no Workload define a página de erro que o cliente vê. -- **Interfaces**: no [Azion Console](https://console.azion.com/), você cria e gerencia as suas Applications na página **Applications**, onde cada Application tem cinco abas: **Main Settings**, **Device Groups**, **Cache Settings**, **Functions Instances** e **Rules Engine**. No Console, a ação de linha **Clone** da lista **Applications** cria uma Application separada com as configurações da original, como mostra [Clone uma aplicação](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/clonar-applications/). [Azion API](https://api.azion.com/) serve as suas Applications em `/v4/workspace/applications`, e [Azion CLI](/pt-br/documentacao/devtools/cli/) as gerencia com comandos como `azion create application`, `azion update application` e `azion create rules-engine`. Você também pode criar e configurar as suas Applications com [`azion.config.js`](/pt-br/documentacao/devtools/cli/azion-config-js/), [Azion Lib](/pt-br/documentacao/devtools/azion-lib/application/) ou [Azion Terraform Provider](/pt-br/documentacao/devtools/terraform/). Se a sua conta não migrou para a API v4, use [Applications | v3](/pt-br/documentacao/plataforma/applications/v3/). -- **Observabilidade**: com Debug Rules ativo, [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/) e [Data Stream](/pt-br/documentacao/plataforma/data-stream/) mostram as regras que cada requisição executou, no campo `$traceback`. Debug Rules começa desativado em uma Application nova. Ele é o campo `debug` da Application na API, e [Main Settings](/pt-br/documentacao/plataforma/applications/main-settings/#debug-rules) mostra onde ativá-lo no Azion Console. Para verificar uma resposta, envie a requisição com `Pragma: azion-debug-cache`: a resposta informa o seu status de cache, como `HIT` ou `MISS`, no header `x-cache`. Em todas as requisições, [Real-Time Metrics](/pt-br/documentacao/plataforma/real-time-metrics/) mostra o tráfego de Cache e de [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/). [Solucione problemas de Applications](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/) lista as ferramentas e as consultas. Para um tráfego que difere do que você vê, consulte [Um problema aparece no tráfego, mas não nas respostas que você solicita](/pt-br/documentacao/plataforma/applications/solucao-de-problemas/#um-problema-aparece-no-trafego-mas-nao-nas-respostas-que-voce-solicita). -- **Limites**: uma Application aceita no máximo 200 regras, somando as duas fases. Cada regra tem de 1 a 5 grupos de 1 a 10 critérios, além de 1 a 10 behaviors. Sem Application Accelerator, um cache setting precisa de um Max Age, o seu campo `modules.cache.max_age`, de no mínimo 60 segundos. Um único objeto em cache pode chegar a 10 GB. [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/) lista cada limite, o que acontece quando ele é ultrapassado e os limites de cada recurso da plataforma aninhado em Applications. -- **Cobrança**: um recurso da plataforma que você ativa pode gerar custos que dependem do uso. A página [Preços da Azion](https://www.azion.com/pt-br/precos/) lista os planos e o uso que cada plano inclui, e [Preços](/pt-br/documentacao/fundamentos/precos/) lista as tarifas e a métrica pela qual cada recurso da plataforma é cobrado. -- **Termos**: o [glossário de Applications](/pt-br/documentacao/plataforma/applications/glossario/) define as palavras que as páginas de Applications usam com um significado específico, como regra, fase, behavior, cache setting, cache key e imagem derivada. +1. A requisição chega a um Workload por um dos domínios dele, e o Workload a encaminha para a Application. Quando o deployment do Workload também define um [Firewall](/pt-br/documentacao/plataforma/firewall/), o Firewall executa as suas regras primeiro e pode recusar a requisição. +2. A Application executa as suas regras da Request Phase em ordem. Quando um behavior, a ação que uma regra executa, encerra o processamento, como faz _Deny (403 Forbidden)_, a Application responde ao cliente e nenhuma regra posterior é executada. +3. Uma regra com _Set Cache Policy_ pode aplicar um cache setting, o conjunto de valores que diz ao Cache como armazenar e servir uma resposta. Cache então procura uma cópia válida da resposta da origem. Se Cache tem uma, essa cópia se torna a resposta, e a origem não recebe nenhuma requisição. +4. Caso contrário, o Connector que uma regra com _Set Connector_ define encaminha a requisição à origem. Se várias regras correspondentes carregam _Set Connector_, somente a última delas é executada. +5. A Application executa as suas regras da Response Phase sobre a resposta, e a resposta chega ao cliente. --- @@ -159,8 +74,10 @@ A [visão geral do Image Processor](/pt-br/documentacao/plataforma/applications/ - + - + + + diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-functions-instances.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-functions-instances.mdx index da54a57a96..4b5b351f2b 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-functions-instances.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/edge-functions-instances.mdx @@ -14,15 +14,17 @@ import DocItem from '@aziontech/webkit/doc-item' Uma Function Instance é a entidade que vincula uma [Function](/pt-br/documentacao/plataforma/functions/) a uma [Application](/pt-br/documentacao/plataforma/applications/) ou a um [Firewall](/pt-br/documentacao/plataforma/firewall/). A Function Instance carrega os Args, os argumentos passados para o contexto da execução da Function em formato JSON: `args` na API, e a seção **Arguments** no Azion Console. Uma Function Instance define o nome, os Args, o schema do formulário e se ela está ativa, e mantém o código da Function como ele está. -Uma regra em [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) invoca a Function Instance, não a Function. A mesma Function pode ser instanciada em mais de uma Application, e cada Function Instance carrega os próprios Args. Uma Function Instance só é executada quando uma regra com _Run Function_ invoca essa Function Instance. +A mesma Function pode ser instanciada em mais de uma Application, e cada Function Instance carrega os próprios Args. Uma Function Instance só é executada quando uma regra em [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/) invoca essa Function Instance, e não a Function, com _Run Function_. -Um Firewall tem as suas próprias Function Instances. Uma Function Instance em um Firewall executa a sua Function antes que a requisição chegue à Application, então a Function pode interromper a requisição ali. Uma Function Instance em uma Application executa a sua Function como parte de servir a requisição. Para as Function Instances de um Firewall, consulte [Instâncias de função no Firewall](/pt-br/documentacao/plataforma/firewall/functions-instances/). Para os limites delas, consulte [Limites de Firewall](/pt-br/documentacao/plataforma/firewall/limites/#regras-e-instancias-de-funcao). +Um Firewall tem as suas próprias Function Instances. Uma Function Instance em um Firewall executa a sua Function antes que a requisição chegue à Application, então a Function pode interromper a requisição ali. Uma Function Instance em uma Application executa a sua Function como parte de servir a requisição. + +Para as Function Instances de um Firewall, consulte [Instâncias de função no Firewall](/pt-br/documentacao/plataforma/firewall/functions-instances/). Para os limites delas, consulte [Limites de Firewall](/pt-br/documentacao/plataforma/firewall/limites/#regras-e-instancias-de-funcao). --- ## Campos da Function Instance -A [API da Azion](https://api.azion.com/) cria uma Function Instance de uma Application sob essa Application. Estes são os campos que você define: +Você cria uma Function Instance de uma Application pela [API da Azion](https://api.azion.com/), sob o path dessa Application. Estes são os campos que você define: | Campo | Tipo | Obrigatório | Descrição | | --- | --- | --- | --- | @@ -75,7 +77,7 @@ A API responde `202` com o objeto criado: } ``` -O valor `"state": "pending"` significa que a alteração leva alguns minutos para propagar antes de entrar em vigor. +O valor `"state": "pending"` significa que a alteração pode levar alguns minutos para propagar antes de entrar em vigor, e a Azion não garante um tempo de propagação. A API serve as Function Instances de uma Application em `/workspace/applications//functions`. No path de uma Function Instance, `` é o ID da Function Instance, não da Function: @@ -114,7 +116,7 @@ Args são a configuração de uma Function Instance. Valores sensíveis, como ch _Run Function_ é o behavior de [Rules Engine](/pt-br/documentacao/plataforma/applications/rules-engine/#run-function) que invoca uma Function Instance. A regra guarda o ID da Function Instance, e a fase e os critérios da regra decidem quando ela é executada. Quando uma requisição atende a esses critérios, a Function é executada na infraestrutura distribuída da Azion. -_Run Function_ está disponível na Request Phase e na Response Phase, e exige [Functions](/pt-br/documentacao/plataforma/functions/) ativado na Application. Na Response Phase, ele executa somente Functions escritas em Lua. Na API da Azion, o behavior é `run_function`, e o atributo `value` dele carrega o ID da Function Instance. Enquanto Functions está desativado, a API também recusa criar uma Function Instance na Application, com HTTP `400` e o erro `29003`, `Edge Functions Module Is Not Enabled`. +_Run Function_ está disponível na Request Phase e na Response Phase, e exige [Functions](/pt-br/documentacao/plataforma/functions/) ativado na Application. Na Response Phase, ele executa somente Functions escritas em Lua. Na API da Azion, o behavior é `run_function`, e o atributo `value` dele carrega o ID da Function Instance. Para as fases de execução, os critérios e a ordem em que os behaviors são executados, consulte [Como Functions funciona](/pt-br/documentacao/plataforma/functions/como-funciona/). @@ -136,6 +138,16 @@ Azion CLI gerencia as Function Instances de uma Application com cinco comandos s --- +## Erros + +A API recusa uma Function Instance com este erro: + +| Código | Título | Status | O que causa | O que fazer | +| --- | --- | --- | --- | --- | +| `29003` | `Edge Functions Module Is Not Enabled` | 400 | Uma Function Instance nova em uma Application com Functions desativado | Ative Functions na Application e, em seguida, crie a Function Instance novamente | + +--- + ## Recursos relacionados diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/l2-caching.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/l2-caching.mdx index 721a0a94b6..f6bd50bdf1 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/l2-caching.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/l2-caching.mdx @@ -2,7 +2,7 @@ title: Tiered Cache description: >- Ative uma segunda camada de cache entre o data center que responde a uma - requisição e a sua origem, escolha a sua topology e purgue-a por cache key. + requisição e a sua origem, escolha a sua topologia e purgue-a por cache key. meta_tags: 'tiered cache, camada de cache, topology, cache settings, max age, purge de cache, real-time purge, cache' namespace: documentation_products_edge_application_l2_caching permalink: /documentacao/plataforma/applications/cache/tiered-cache/ @@ -14,9 +14,7 @@ import DocItem from '@aziontech/webkit/doc-item' **Tiered Cache** é uma feature de [Cache](/pt-br/documentacao/plataforma/applications/cache/) que adiciona uma segunda camada de cache entre o data center que responde a uma requisição e a sua origem. A primeira camada é o cache desse data center. A segunda camada fica na região que a `topology` de um cache setting seleciona. -Quando uma requisição resulta em um miss na primeira camada, o data center consulta a camada do Tiered Cache antes que a requisição siga para a origem. Uma cópia válida do objeto requisitado nessa camada responde ao miss, e a origem não recebe nenhuma requisição. Você ativa a camada por cache setting, e ela se aplica aos objetos que esse setting coloca em cache. Para saber como as duas camadas respondem a uma requisição, consulte [Expiração e atualização](/pt-br/documentacao/plataforma/applications/cache/expiracao-e-atualizacao/#tiered-cache). - -Uma resposta da camada do Tiered Cache chega com menos latência do que uma resposta da origem, e menos requisições chegam à origem. A origem lida com menos carga a um custo de infraestrutura menor. O preço é um salto extra em um miss na primeira camada. Com [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) ativo, Tiered Cache também define um piso de 3 segundos no tempo de vida (TTL) do cache setting. +Você ativa a camada por cache setting, e ela se aplica aos objetos que esse setting coloca em cache. Para saber como as duas camadas respondem a uma requisição, e o que a camada custa e economiza, consulte [Expiração e atualização](/pt-br/documentacao/plataforma/applications/cache/expiracao-e-atualizacao/#tiered-cache). --- @@ -26,20 +24,22 @@ Um cache setting ativa Tiered Cache no seu objeto `modules.cache.tiered_cache`, | Interface | Onde | Valor | | --- | --- | --- | -| [Azion Console](https://console.azion.com/) | A seção **Cache** do drawer **Create Cache Settings**, na aba **Cache Settings** de uma Application em [Applications](/pt-br/documentacao/plataforma/applications/) | O toggle **Tiered Cache**, desativado em um setting novo, e o select **Tiered Cache Region**, com `nearest-region` como padrão. Ativar o toggle desabilita _Honor cache policies_ e seleciona _Override cache behavior_ | +| [Azion Console](https://console.azion.com/) | A seção **Cache** do drawer **Create Cache Settings**, na aba **Cache Settings** de uma Application em [Applications](/pt-br/documentacao/plataforma/applications/) | O toggle **Tiered Cache**, desativado em um setting novo, e o select **Tiered Cache Region**, com `nearest-region` como padrão | | [Azion API v4](/pt-br/documentacao/devtools/api/) | `POST /v4/workspace/applications/{application_id}/cache_settings` | `modules.cache.tiered_cache.enabled`, `true` ou `false`, e `modules.cache.tiered_cache.topology`, `nearest-region` quando o corpo não o envia | | [Azion CLI](/pt-br/documentacao/devtools/cli/) | `azion create cache-setting --file` com o corpo JSON | O mesmo objeto `tiered_cache`. A flag `--tiered-caching-enabled` sozinha é recusada com o erro `21001` | | `azion.config.js` | Uma entrada do array `cache`, do tipo `AzionCache` | `tieredCache: { enabled, topology }` | :::note[nota] -Duas condições se aplicam ao cache setting. O seu `modules.cache.behavior` precisa ser `override`, porque a API recusa Tiered Cache sob `honor` com o erro `21001`. A CLI só define o comportamento de cache no corpo JSON do `--file`. Com [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) ativo na Application, o `modules.cache.max_age` do cache setting precisa ser de pelo menos 3 segundos, ou a API retorna o erro `21020`. Sem Application Accelerator, vale o piso de 60 segundos de todo cache setting, e a API retorna `21021`. +Um cache setting com Tiered Cache ativo precisa de `override` em `modules.cache.behavior`, porque a API recusa Tiered Cache sob `honor` com o erro `21001`. No Azion Console, ativar o toggle **Tiered Cache** desabilita _Honor cache policies_ e seleciona _Override cache behavior_. A CLI só define o comportamento de cache no corpo JSON do `--file`. + +Com [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/) ativo na Application, o `modules.cache.max_age` do cache setting precisa ser de pelo menos 3 segundos, ou a API retorna o erro `21020`. Sem Application Accelerator, vale o piso de 60 segundos de todo cache setting, e a API retorna `21021`. ::: Tiered Cache está incluído em todos os planos de serviço. Para todos os campos de um cache setting, com o título e a correção de cada erro, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/). Para os passos no Console que aplicam um setting a um path, consulte [Configure políticas de cache para uma aplicação](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/cache-settings/). --- -## Topology +## Topologia A `topology` de um cache setting seleciona onde a camada do Tiered Cache mantém os objetos que esse setting coloca em cache. Azion Console, a API, o corpo JSON da CLI e o `azion.config.js` aceitam valores como `nearest-region` e `us-east-1`, e a [referência da Azion API](https://api.azion.com/) lista todos os valores aceitos. Um valor que a API não aceita retorna o erro `10039`, `Invalid Choice`. @@ -47,7 +47,9 @@ A `topology` de um cache setting seleciona onde a camada do Tiered Cache mantém ## TTL -O tempo de vida (TTL) de um objeto na camada do Tiered Cache é o Max Age do seu cache setting, o campo `modules.cache.max_age`. Enquanto Tiered Cache e Application Accelerator estão ativos, esse campo tem um piso de 3 segundos. Um cache setting novo começa em 60 segundos, o padrão do Max Age no Azion Console, na API e na CLI. Por exemplo, em uma Application com Application Accelerator ativo, um Max Age de 2 segundos com Tiered Cache ativo é recusado com o erro `21020`. O mesmo setting com 3 segundos é aceito. +O tempo de vida (TTL) de um objeto na camada do Tiered Cache é o Max Age do seu cache setting, o campo `modules.cache.max_age`. Enquanto Tiered Cache e Application Accelerator estão ativos, esse campo tem um piso de 3 segundos. Um cache setting novo começa em 60 segundos, o padrão do Max Age no Azion Console, na API e na CLI. + +Por exemplo, em uma Application com Application Accelerator ativo, um Max Age de 2 segundos com Tiered Cache ativo é recusado com o erro `21020`. O mesmo setting com 3 segundos é aceito. O teto é o teto do próprio TTL de cache. Para o valor e o erro além dele, consulte [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/#cache). diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/main-settings.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/main-settings.mdx index efe0205f90..fe08a1ad5c 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/main-settings.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/main-settings.mdx @@ -17,9 +17,28 @@ Main Settings é o conjunto de valores que se aplicam a uma [Application](/pt-br --- +## Interfaces + +Você cria e configura uma Application no Azion Console, na Azion API, na Azion CLI, no `azion.config.js`, na Azion Lib ou no Azion Terraform Provider. + +| Interface | Onde ela alcança as suas Applications | +| --- | --- | +| [Azion Console](https://console.azion.com/) | A página **Applications**, com cinco abas para cada Application | +| [Azion API](https://api.azion.com/) | `/v4/workspace/applications`, que a seção API detalha | +| [Azion CLI](/pt-br/documentacao/devtools/cli/) | Comandos como `azion create application`, `azion update application` e `azion create rules-engine` | +| [`azion.config.js`](/pt-br/documentacao/devtools/cli/azion-config-js/) | O arquivo de configuração que a Azion CLI lê | +| [Azion Lib](/pt-br/documentacao/devtools/azion-lib/application/) | Cria e configura Applications a partir do seu código | +| [Azion Terraform Provider](/pt-br/documentacao/devtools/terraform/) | Cria e configura Applications | + +No Azion Console, cada Application tem cinco abas: **Main Settings**, **Device Groups**, **Cache Settings**, **Functions Instances** e **Rules Engine**. Esta página documenta a aba **Main Settings**. A ação **Clone** de uma linha da lista **Applications** cria uma Application separada com as configurações da original. Para clonar uma Application, consulte [Clone uma aplicação](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/clonar-applications/). + +Uma conta que não migrou para a API v4 gerencia as suas Applications em [Applications | v3](/pt-br/documentacao/plataforma/applications/v3/). + +--- + ## Seções e campos -No Azion Console, a aba **Main Settings** de uma Application tem quatro seções: **General**, **Modules**, **Debug Rules** e **Status**. A aba traz **Cancel** e **Save**, e uma alteração é salva com **Save**. +No Azion Console, a aba **Main Settings** de uma Application tem quatro seções: **General**, **Modules**, **Debug Rules** e **Status**. A aba traz **Cancel** e **Save**, e **Save** mantém uma alteração. Cada seção corresponde a um ou mais campos da Application na API. A última coluna traz o valor que cada campo assume quando uma requisição de criação envia apenas `name` e `active`. @@ -38,22 +57,26 @@ O status, o boolean `active` na API, desativa a Application e a ativa de novo se ## Recursos da plataforma -No Azion Console, os switches que ativam ou desativam recursos da plataforma em uma Application ficam na seção **Modules**, e cada Application mantém o próprio conjunto. O grupo **Default Modules** dessa seção tem um switch por recurso da plataforma: **Application Accelerator**, **Cache**, **Functions** e **Image Processor**. Um grupo **Subscription modules** traz uma ação **Contact sales**, e a seção informa `Some modules require subscription.` +Cada Application ativa o próprio conjunto de quatro recursos da plataforma, no objeto `modules` da API e na seção **Modules** do Azion Console. O grupo **Default Modules** dessa seção tem um switch por recurso da plataforma: **Application Accelerator**, **Cache**, **Functions** e **Image Processor**. Um grupo **Subscription modules** traz uma ação **Contact sales**, e a seção informa `Some modules require subscription.` | Recurso da plataforma | Chave em `modules` | Flag da CLI | O que cobre na Application | | --- | --- | --- | --- | -| Application Accelerator | `application_accelerator` | `--application-accelerator` | Os behaviors marcados com `- Required Application Accelerator` e a variável `${request_uri}` | +| Application Accelerator | `application_accelerator` | `--application-accelerator` | Os behaviors marcados com `- Required Application Accelerator` e as variáveis `${request_uri}` e `${device_group}` | | Cache | `cache` | `--cache` | O armazenamento em cache do conteúdo que a Application entrega | | Functions | `functions` | `--function` na criação, `--functions` na atualização | As Function Instances, invocadas por um behavior _Run Function_ | | [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) | `image_processor` | `--image-processor` | O behavior _Optimize Images_ | -No Azion Console, o formulário do **Rules Engine** marca um behavior cujo recurso da plataforma está desativado com `- Required Application Accelerator`, `- Required Function` ou `- Required Image Processor`. Um cache setting também precisa de Application Accelerator para as variações do seu objeto `modules.application_accelerator`, e para um Max Age, o seu campo `modules.cache.max_age`, menor que 60 segundos. +No Azion Console, o formulário do **Rules Engine** marca um behavior cujo recurso da plataforma está desativado com `- Required Application Accelerator`, `- Required Function` ou `- Required Image Processor`. Os cache settings e as Function Instances pertencem à Application, fora de Main Settings. Um behavior _Set Cache Policy_ aplica um cache setting, e um behavior _Run Function_ invoca uma Function Instance. [Primeiros passos com Cache](/pt-br/documentacao/plataforma/applications/cache/primeiros-passos/) e [Instancie uma função em uma aplicação](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/instanciar-functions/) mostram onde criar cada um no Azion Console. -Cache fica sempre ativado em uma Application: a API recusa `modules.cache.enabled` definido como `false` com o erro `31001`, `Cache Cannot Be False`. Azion Console mostra o switch **Cache** travado como ativado, com a nota `Automatically enabled in all accounts.` Você pode ativar outro recurso da plataforma quando a sua conta oferece suporte a ele, e desativá-lo quando nada na Application depende dele. Ativar um recurso da plataforma pode gerar custos relacionados ao uso. Para mais informações, consulte [Preços](/pt-br/documentacao/fundamentos/precos/). +:::note[nota] +Cache fica sempre ativado em uma Application: a API recusa `modules.cache.enabled` definido como `false` com o erro `31001`, `Cache Cannot Be False`. Azion Console mostra o switch **Cache** travado como ativado, com a nota `Automatically enabled in all accounts.` +::: + +Você pode ativar outro recurso da plataforma quando a sua conta oferece suporte a ele, e desativá-lo quando nada na Application depende dele. Ativar um recurso da plataforma pode gerar custos relacionados ao uso. Para mais informações, consulte [Preços](/pt-br/documentacao/fundamentos/precos/). -Enquanto Application Accelerator está desativado, a API recusa uma regra de requisição cujo critério lê `${request_uri}`. Ela também recusa um cache setting que varia o cache por método, query string, cookie ou device group, ou que define um Max Age menor que 60 segundos. Cada recusa traz um dos códigos da seção Erros, e a mesma regra com `${uri}` é aceita. Para as variáveis e os behaviors que cada recurso da plataforma adiciona, consulte [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/). +Enquanto Application Accelerator está desativado, a API recusa uma regra de requisição cujo critério lê `${request_uri}` ou `${device_group}`. Ela também recusa um cache setting que varia o cache por método, query string, cookie ou device group, no seu objeto `modules.application_accelerator`, ou que define um Max Age, o seu campo `modules.cache.max_age`, menor que 60 segundos. Cada recusa traz um dos códigos da seção Erros, e a mesma regra com `${uri}` é aceita. Para as variáveis e os behaviors que cada recurso da plataforma adiciona, consulte [Rules Engine para Applications](/pt-br/documentacao/plataforma/applications/rules-engine/). [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) não é um dos quatro switches de `modules` de uma Application: é uma feature de Cache, e cada cache setting o ativa no seu campo `modules.cache.tiered_cache.enabled`. @@ -61,7 +84,7 @@ Enquanto Application Accelerator está desativado, a API recusa uma regra de req ## Debug Rules -Debug Rules registra as regras do Rules Engine executadas em cada requisição à Application. A configuração fica desativada quando você cria uma Application, e a API a guarda no boolean `debug`. No Azion Console, o switch **Active** da seção **Debug Rules** define essa configuração. Na [Azion CLI](/pt-br/documentacao/devtools/cli/), `--debug-enabled` define essa configuração em `azion create application` e em `azion update application`. +Debug Rules é a configuração de uma Application que registra as regras do Rules Engine executadas em cada requisição. A configuração fica desativada quando você cria uma Application, e a API a guarda no boolean `debug`. No Azion Console, o switch **Active** da seção **Debug Rules** define essa configuração. Na [Azion CLI](/pt-br/documentacao/devtools/cli/), `--debug-enabled` define essa configuração em `azion create application` e em `azion update application`. Com Debug Rules ativado, as regras executadas em uma requisição aparecem no campo `$traceback` do [Data Stream](/pt-br/documentacao/plataforma/data-stream/) e do [Real-Time Events](/pt-br/documentacao/plataforma/real-time-events/). A API GraphQL do Real-Time Events retorna as mesmas regras no campo `stacktrace`. Uma regra que não está nessa lista não foi executada na requisição. @@ -149,7 +172,11 @@ A API responde `202` com `state` definido como `pending`. Um corpo com `function | `azion delete application` | Exclui a Application que `--application-id` nomeia | `--application-id`, `--cascade` | | `azion clone application` | Copia uma Application com o nome em `--name` | `--application-id`, `--name` | -A flag de Functions é `--function` em `azion create application` e `--functions` em `azion update application`. Em `azion delete application`, `--cascade` também exclui os recursos que `azion deploy` criou, e o padrão dela é `true`. +A flag de Functions é `--function` em `azion create application` e `--functions` em `azion update application`. + +:::caution[Atenção] +Em `azion delete application`, `--cascade` também exclui os recursos que `azion deploy` criou, e o padrão dela é `true`. +::: Este comando ativa Application Accelerator: @@ -182,7 +209,7 @@ Em uma Application com os quatro recursos da plataforma ativados, o objeto fica ## Erros -Um recurso da plataforma desativado na Application aparece como a recusa do objeto que precisa dele, com `400`. Cada uma dessas recusas nomeia Application Accelerator, exceto `31001`, que recusa desativar Cache. Este corpo responde a uma regra de requisição com `${request_uri}`: +Um recurso da plataforma desativado na Application aparece como a recusa do objeto que precisa dele, com `400` ou `403`. Cada uma dessas recusas nomeia o recurso da plataforma que deve ser ativado, exceto `31001`, que recusa desativar Cache. Este corpo responde a uma regra de requisição com `${request_uri}`: ```json { @@ -207,11 +234,15 @@ Um recurso da plataforma desativado na Application aparece como a recusa do obje | Código | Título | Status | O que causa | O que fazer | | --- | --- | --- | --- | --- | -| `25047` | `Missing Required Modules` | 400 | Uma regra de requisição cujos critérios leem `${request_uri}`, em uma Application com Application Accelerator desativado | Ative Application Accelerator, ou faça a correspondência com `${uri}`, que a API aceita sem ele | -| `21013` | `This Configuration Requires The Edge Application's Application Accelerator Module` | 400 | Um cache setting que varia o cache por método, query string, cookie ou device group, em uma Application com Application Accelerator desativado. O pointer nomeia a variação, como `/data/modules/application_accelerator/cache_vary_by_method` | Ative Application Accelerator e, em seguida, salve o cache setting novamente | -| `21021` | `Edge Cache Max Age Lower Than The Minimum Allowed By Application's Application Accelerator Module` | 400 | Um cache setting cujo `modules.cache.max_age` é menor que 60, em uma Application com Application Accelerator desativado. `meta.min_value` é `60` | Ative Application Accelerator, ou defina `modules.cache.max_age` como 60 segundos ou mais | +| `25047` | `Missing Required Modules` | 400 | Uma regra com `${request_uri}` ou `${device_group}`, com Application Accelerator desativado | Ative Application Accelerator, ou faça a correspondência com `${uri}`, que a API aceita sem ele | +| `21013` | `This Configuration Requires The Edge Application's Application Accelerator Module` | 400 | Uma variação de cache por método, query string, cookie ou device group, com Application Accelerator desativado | Ative Application Accelerator e, em seguida, salve o cache setting novamente | +| `21021` | `Edge Cache Max Age Lower Than The Minimum Allowed By Application's Application Accelerator Module` | 400 | Um cache setting com `modules.cache.max_age` menor que 60, com Application Accelerator desativado | Ative Application Accelerator, ou defina `modules.cache.max_age` como 60 segundos ou mais | +| `27002` | `Application Acceleration Not Enabled` | 403 | Um device group novo, com Application Accelerator desativado | Ative Application Accelerator e, em seguida, crie o device group novamente | +| `29003` | `Edge Functions Module Is Not Enabled` | 400 | Uma Function Instance nova, com Functions desativado | Ative Functions e, em seguida, crie a Function Instance novamente | | `31001` | `Cache Cannot Be False` | 400 | Um `PATCH` que define `modules.cache.enabled` como `false` | Mantenha Cache ativado: ele não pode ser desativado | +Para `21013`, o pointer nomeia a variação, como `/data/modules/application_accelerator/cache_vary_by_method`. Para `21021`, `meta.min_value` é `60`. + --- ## Recursos relacionados diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/real-time-purge.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/real-time-purge.mdx index c567864896..09865ca3fc 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/real-time-purge.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/real-time-purge.mdx @@ -12,9 +12,7 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -**Real-Time Purge** é um recurso da plataforma que remove um objeto em cache do [Cache](/pt-br/documentacao/plataforma/applications/cache/), ou do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/), antes do fim do seu tempo de vida (TTL). Quando o objeto não está mais no Cache nem no Tiered Cache, a requisição seguinte por esse objeto busca a versão atual na origem. Use um purge para entregar uma atualização que a origem já tem, para remover um objeto obsoleto ou para manter o controle do que a Azion entrega em conteúdo dinâmico. - -Um purge recebe um de três argumentos: uma lista de URLs, uma lista de cache keys ou uma expressão com wildcard. A Azion confirma cada purge, o coloca em fila e o lista no histórico de purges quando ele termina. Para os passos, consulte [Purgue conteúdo em cache](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/purgar-conteudo-em-cache/). Para o formato de uma key, consulte [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/). +**Real-Time Purge** é um recurso da plataforma que remove um objeto em cache do [Cache](/pt-br/documentacao/plataforma/applications/cache/) ou da camada do [Tiered Cache](/pt-br/documentacao/plataforma/applications/cache/tiered-cache/) antes que ele expire. Quando um objeto não está em nenhuma das camadas, a requisição seguinte por ele busca a versão atual na origem. Um purge recebe um de três argumentos: uma lista de URLs, uma lista de cache keys ou uma expressão com wildcard. Para os passos, consulte [Purgue conteúdo em cache](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/purgar-conteudo-em-cache/) e, para o formato de uma key, [Cache keys](/pt-br/documentacao/plataforma/applications/cache/cache-keys/). --- @@ -59,9 +57,9 @@ O segmento `purge_type` do path da API, a flag da CLI e o tipo de purge do Conso ### Purge por URL -Um purge por URL recebe uma lista de URLs e não é recursivo: apenas as URLs da lista saem do cache. A Azion converte cada URL na sua cache key sem variação de conteúdo. Então uma variação por cookie, device group, formato de imagem ou corpo da requisição não expira com ele. Purgue essas variações com um purge por cache key ou por wildcard. +Um purge por URL recebe uma lista de URLs e não é recursivo: apenas as URLs da lista saem do cache. A Azion converte cada URL na sua cache key sem variação de conteúdo. Então uma cópia que varia por cookie, device group, formato de imagem ou corpo da requisição não expira com ele. Purgue essas cópias com um purge por cache key ou por wildcard. -Uma variação por query string faz parte da URL, então ela expira quando os argumentos estão na mesma ordem da cache key. Com o `sort_enabled` ativo no cache setting, envie os argumentos em ordem alfabética, ou use um purge por cache key ou por wildcard. Para o campo `sort_enabled`, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#application-accelerator). +Uma cópia que varia por query string carrega os argumentos na sua URL, então ela expira quando os argumentos estão na mesma ordem da cache key. Com o `sort_enabled` ativo no cache setting, envie os argumentos em ordem alfabética, ou use um purge por cache key ou por wildcard. Para o campo `sort_enabled`, consulte [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#application-accelerator). Uma URL é `scheme://host` ou `host`, com um `/path` e uma `?query-string` opcionais. Sem scheme, a Azion purga as cópias em HTTP e em HTTPS. Um asterisco (`*`) em um purge por URL é um caractere literal, e não um wildcard. A lista abaixo carrega quatro argumentos válidos de URL: @@ -72,11 +70,15 @@ Uma URL é `scheme://host` ou `host`, com um `/path` e uma `?query-string` opcio ### Purge por cache key -Um purge por cache key recebe uma lista de cache keys. Uma key nomeia uma variação de um objeto. Com Advanced Cache Key, uma feature de [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/), uma key pode variar por query string, ordenada ou não, e por cookie, device group ou método da requisição. Pelo [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/), uma key também pode variar por formato de imagem. Para purgar todas as variações de um objeto, liste cada key. Um purge por cache key é o único tipo que alcança a camada do Tiered Cache. +Um purge por cache key recebe uma lista de cache keys. Uma key nomeia uma cópia de um objeto. Um purge por cache key é o único tipo que alcança a camada do Tiered Cache. + +Com Advanced Cache Key, uma feature de [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/), uma key pode variar por query string, ordenada ou não, e por cookie, device group ou método da requisição. Pelo [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/), uma key também pode variar por formato de imagem. Para purgar todas as cópias de um objeto, liste a key de cada uma. ### Purge por wildcard -Um purge por wildcard recebe uma expressão: `scheme://host` ou `host`, com um `/path` e uma `?query-string` opcionais. A expressão carrega um asterisco (`*`) no path ou na query string. Vários asteriscos casam um path mais complexo. Cada requisição carrega uma expressão, e um purge por wildcard alcança apenas a camada do Cache, e não a do Tiered Cache. A lista abaixo carrega dez expressões válidas: +Um purge por wildcard recebe uma expressão: `scheme://host` ou `host`, com um `/path` e uma `?query-string` opcionais. A expressão carrega um asterisco (`*`) no path ou na query string. Vários asteriscos casam um path mais complexo. Cada requisição carrega uma expressão, e um purge por wildcard alcança apenas a camada do Cache, e não a do Tiered Cache. + +A lista abaixo carrega dez expressões válidas: - `www.example.com/*` - `static.example.com/include/*.css` @@ -93,27 +95,29 @@ Um purge por wildcard recebe uma expressão: `scheme://host` ou `host`, com um ` ## Purgue conteúdo que varia -Quando um cache setting varia a cache key, um objeto tem uma key por variação. A tabela nomeia o purge que alcança cada tipo de variação. +Quando um cache setting varia a cache key, um objeto tem uma key por cópia. A tabela nomeia o purge que alcança cada tipo de variação. | Variação | Como purgar | | --- | --- | -| Cookies | Um purge por cache key que lista cada variação, ou um purge por wildcard com `@@*` no fim | -| Query string | Um purge por cache key que lista cada variação, um purge por wildcard com `?*` no fim, ou um purge por URL que nomeia apenas os argumentos da key, em ordem alfabética quando o `sort_enabled` está ativo | -| Device group | Um purge por cache key que lista cada variação, ou um purge por wildcard com `@@*` no fim | -| Image Processor | Um purge por cache key que lista cada variação, ou um purge por wildcard com `*` no fim | +| Cookies | Um purge por cache key que lista a key de cada cópia, ou um purge por wildcard com `@@*` no fim | +| Query string | Um purge por cache key que lista a key de cada cópia, um purge por wildcard com `?*` no fim, ou um purge por URL que nomeia apenas os argumentos da key, em ordem alfabética quando o `sort_enabled` está ativo | +| Device group | Um purge por cache key que lista a key de cada cópia, ou um purge por wildcard com `@@*` no fim | +| Image Processor | Um purge por cache key que lista a key de cada cópia, ou um purge por wildcard com `*` no fim | | Large File Optimization | Um purge por cache key que lista a key de cada fragmento, ou um purge por wildcard como `static.example.com/media/file.mp4*` | -| `POST` e `OPTIONS` em cache | Um purge por cache key que lista cada variação, ou um purge por wildcard com `@@*` no fim | +| `POST` e `OPTIONS` em cache | Um purge por cache key que lista a key de cada cópia, ou um purge por wildcard com `@@*` no fim | -As variações por query string, por cookie, por device group e por método da requisição vêm de Advanced Cache Key, em [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/). Application Accelerator também coloca em cache respostas `POST` e `OPTIONS`; sem ele, a Azion coloca em cache apenas `GET` e `HEAD`. Para os behaviors, consulte [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/). +As variações por query string, por cookie, por device group e por método da requisição vêm de Advanced Cache Key, em [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/). Application Accelerator também coloca em cache respostas `POST` e `OPTIONS`. Sem ele, a Azion coloca em cache apenas `GET` e `HEAD`. Para os behaviors, consulte [Configurações do Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/). -Uma imagem que [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) entrega tem uma key por processamento e por formato quando o cache setting nomeia `ims` na allowlist de query string. Quando o cache setting não varia a key por query string, o valor de `ims` não faz parte da key. Todos os tamanhos e processamentos do path então compartilham uma key, e o primeiro armazenado responde a todos os valores de `ims`. Com `ims` na allowlist, a key carrega o host e o path, depois `@@`, a query string `ims` e, no fim, o formato convertido, sem separador. As quatro keys abaixo pertencem a uma imagem: +Uma imagem que [Image Processor](/pt-br/documentacao/plataforma/applications/image-processor/) entrega tem uma key por processamento e por formato quando o cache setting nomeia o parâmetro `ims` na allowlist de query string. Quando o cache setting não varia a key por query string, o valor de `ims` não faz parte da key. Todos os tamanhos e processamentos do path então compartilham uma key, e o primeiro armazenado responde a todos os valores de `ims`. + +Com `ims` na allowlist, a key carrega o host e o path, depois `@@`, o parâmetro `ims` e, no fim, o formato convertido, sem separador. As quatro keys abaixo pertencem a uma imagem: - `httpstatic.example.com/static/images/image.jpg@@` - `httpstatic.example.com/static/images/image.jpg@@webp` - `httpstatic.example.com/static/images/image.jpg@@?ims=88x` - `httpstatic.example.com/static/images/image.jpg@@?ims=88xwebp` -Com a Large File Optimization ativa no cache setting, a Azion coloca um objeto grande em cache em fragmentos, cada um com a sua própria key. O arquivo pode permanecer em cache depois de um purge da sua URL. Para purgá-lo, liste a key de cada fragmento, ou use o wildcard `static.example.com/media/file.mp4*`. Esse wildcard limpa cada fragmento de um arquivo. +Com a Large File Optimization ativa no cache setting, a Azion coloca um objeto grande em cache em fragmentos, cada um com a sua própria key. O arquivo pode permanecer em cache depois de um purge da sua URL, enquanto o wildcard da linha Large File Optimization limpa cada fragmento de um arquivo. :::caution[Atenção] Um purge de fragmentos individuais pode deixar fragmentos antigos e novos lado a lado. Quando o arquivo muda na origem, um fragmento que não foi purgado permanece no cache ao lado dos fragmentos buscados novamente. @@ -126,25 +130,39 @@ Um purge de fragmentos individuais pode deixar fragmentos antigos e novos lado a A API lê o tipo de purge no path e os argumentos em `items`. O corpo abaixo envia um purge por URL pelo `POST /v4/workspace/purge/url`: ```json -{"items":["https://www.example.com/include/site.js"],"layer":"cache"} +{ + "items": ["https://www.example.com/include/site.js"], + "layer": "cache" +} ``` -Um purge por wildcard vai pelo `POST /v4/workspace/purge/wildcard`; sem `layer`, a API purga o `cache`: +Um purge por wildcard vai pelo `POST /v4/workspace/purge/wildcard`. Sem `layer`, a API purga o `cache`: ```json -{"items":["www.example.com/include/*.css"]} +{ + "items": ["www.example.com/include/*.css"] +} ``` Um purge por cache key vai pelo `POST /v4/workspace/purge/cachekey`: ```json -{"items":["httpswww.example.com/include/site.js"],"layer":"cache"} +{ + "items": ["httpswww.example.com/include/site.js"], + "layer": "cache" +} ``` Cada requisição responde com HTTP `201`, `state` igual a `executed` e os itens e a camada em `data`: ```json -{"state":"executed","data":{"items":[...],"layer":"cache"}} +{ + "state": "executed", + "data": { + "items": [...], + "layer": "cache" + } +} ``` A CLI envia os mesmos três purges pela linha de comando, o último para a camada do Tiered Cache: @@ -190,10 +208,11 @@ Os limites abaixo se aplicam a requisições de purge. Cada linha nomeia a respo | Valor | Limite | Além do limite | | --- | --- | --- | -| Tamanho de uma URL ou cache key | 4.096 caracteres | A API aceita uma URL mais longa quando recebe a requisição: um purge de uma URL de 4.098 caracteres retorna HTTP `201`. | | Objetos por requisição de purge por URL e cache key | 50 objetos | HTTP `400`, erro `10065` | | Expressões com wildcard por requisição | 1 | HTTP `400`, erro `10065` | +Uma URL ou uma cache key aceita até 4.096 caracteres. A API não recusa uma URL mais longa quando recebe a requisição e responde HTTP `201`. + Outros seis limites definem a taxa de requisições de purge, o tamanho de um wildcard e quanto histórico de purges a Azion mantém. | Valor | Limite | diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/rules-engine-edge-app.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/rules-engine-edge-app.mdx index 2bf30f1f44..be5dbaa64b 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/rules-engine-edge-app.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/rules-engine-edge-app.mdx @@ -10,7 +10,9 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -Rules Engine para Applications é uma feature de Applications que guarda as regras de uma [Application](/pt-br/documentacao/plataforma/applications/). Uma regra é uma lógica condicional que a Application aplica a uma requisição ou à resposta dela. Por exemplo, uma regra pode enviar a requisição a um [Connector](/pt-br/documentacao/plataforma/connectors/), aplicar um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) ou invocar uma [Function Instance](/pt-br/documentacao/plataforma/applications/functions-instances/). Cada regra tem critérios, o _se_ dela, e behaviors, o _então_. Ela executa os seus behaviors somente quando uma requisição corresponde aos seus critérios. Toda regra pertence a uma fase: a Request Phase age sobre a requisição, e a Response Phase age sobre a resposta. +Rules Engine para Applications é uma feature de Applications que guarda as regras de uma [Application](/pt-br/documentacao/plataforma/applications/). Uma regra é uma entrada no Rules Engine para Applications que executa os seus behaviors, em uma fase, sobre as requisições às quais os seus critérios correspondem. Cada regra tem critérios, o _se_ dela, e behaviors, o _então_. As duas fases são a Request Phase, que age sobre a requisição, e a Response Phase, que age sobre a resposta. + +Por exemplo, uma regra pode enviar a requisição a um [Connector](/pt-br/documentacao/plataforma/connectors/), aplicar um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) ou invocar uma [Function Instance](/pt-br/documentacao/plataforma/applications/functions-instances/). O modelo corresponde ao roteamento por path de um proxy reverso: cada critério é uma condição de correspondência, cada behavior é uma ação, e um Connector guarda o endereço do servidor de backend. Algumas variáveis e alguns behaviors exigem um recurso da plataforma ativado na Application, e cada tabela desta página indica qual. Para a ordem em que uma Application executa as suas regras e os seus behaviors, consulte [Como Applications funciona](/pt-br/documentacao/plataforma/applications/como-funciona/). @@ -20,7 +22,7 @@ Quando o deployment de um [Workload](/pt-br/documentacao/plataforma/workloads/) ## Campos da regra -Uma Application nova não tem regras, e [Crie regras de request e response](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/rules-engine/) mostra como criar uma no Azion Console. Na API, uma regra é um objeto JSON: uma requisição define cinco dos seus campos, e a plataforma define e retorna os outros cinco. Para os campos que você define, a coluna Descrição também indica o rótulo de cada um no formulário de regra do Azion Console. +Na API, uma regra tem dez campos: uma requisição define cinco, e a plataforma define e retorna os outros cinco. Uma Application nova não tem regras, e [Crie regras de request e response](/pt-br/documentacao/guias/desenvolvimento-de-aplicacoes/primeiros-passos/rules-engine/) mostra como criar uma no Azion Console. Para os campos que você define, a coluna Descrição também indica o rótulo de cada um no formulário de regra do Azion Console. | Campo | Tipo | Obrigatório | Descrição | | --- | --- | --- | --- | @@ -35,7 +37,9 @@ Uma Application nova não tem regras, e [Crie regras de request e response](/pt- | `last_modified` | date-time | Somente leitura | Quando a regra foi alterada pela última vez | | `created_at` | date-time | Somente leitura | Quando a regra foi criada | -A lista de regras do Azion Console não mostra `id`, e `azion list rules-engine` o imprime como `ID`. Dê a cada regra um nome único. Com mais de 1.000 caracteres em `description`, Azion Console mostra `Description should not exceed 1000 characters`. +A lista de regras do Azion Console não mostra `id`, e `azion list rules-engine` o imprime como `ID`. + +Dê a cada regra um nome único. Com mais de 1.000 caracteres em `description`, Azion Console mostra `Description should not exceed 1000 characters`. A plataforma atribui `order` à medida que as regras são criadas: a primeira regra de uma fase carrega `0`, e a regra seguinte carrega `1`. Azion Console numera as mesmas posições a partir de `1`, então a regra cujo `order` é `0` é a que a lista dele mostra como `1`. A lista de regras do Azion Console permite mover uma regra, e uma posição além do fim da lista coloca a regra em último lugar. A API reordena uma fase com uma única chamada, que a seção API lista. @@ -43,7 +47,7 @@ A plataforma atribui `order` à medida que as regras são criadas: a primeira re ## Fases -Você define a fase de uma regra quando a cria, e não pode mudá-la depois. Para executar a mesma lógica na outra fase, crie uma regra nova nessa fase. No Azion Console, a lista de regras agrupa as regras por fase, e a API mantém cada fase em uma coleção própria. +Uma regra é executada na Request Phase ou na Response Phase, que você define ao criar a regra e não pode mudar. Para executar a mesma lógica na outra fase, crie uma regra nova nessa fase. No Azion Console, a lista de regras agrupa as regras por fase, e a API mantém cada fase em uma coleção própria. | Fase | Sobre o que as suas regras agem | Coleção na API | | --- | --- | --- | @@ -56,17 +60,28 @@ Cada fase oferece o seu próprio conjunto de variáveis e behaviors. Um valor qu ## Critérios -Um critério é uma condição que uma requisição precisa atender: uma variável, um operador e, para a maioria dos operadores, um argumento com o qual a variável é comparada. Na API, um critério é um objeto com quatro chaves: `variable`, `operator`, `conditional` e `argument`. +Um critério é uma condição que a requisição precisa atender: uma variável, um operador e, na maioria dos operadores, um argumento de comparação. Na API, um critério é um objeto com quatro chaves: `variable`, `operator`, `conditional` e `argument`. Este critério corresponde a uma requisição de um navegador desktop, com uma expressão regular sobre o header `User-Agent`: ```json -[[{ "variable": "${http_user_agent}", "conditional": "if", "operator": "matches", "argument": "(Chrome|Mozilla)" }]] +[ + [ + { + "variable": "${http_user_agent}", + "conditional": "if", + "operator": "matches", + "argument": "(Chrome|Mozilla)" + } + ] +] ``` ### Variáveis -Uma variável é um valor da requisição ou da resposta, escrito `${name}`. A coluna Fases indica onde um critério pode lê-la. `${request_uri}` e `${device_group}` exigem [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/) ativado na Application. Uma regra que lê uma das duas em uma Application com Application Accelerator desativado é recusada. A API responde HTTP `400` com o código de erro `25047`, `Missing Required Modules`, e a seção Erros traz o corpo completo. `${uri}` não exige nenhum recurso da plataforma, então é a variável de URI para uma Application sem Application Accelerator. +Uma variável é um valor da requisição ou da resposta, escrito `${name}`. A coluna Fases indica onde um critério pode lê-la. + +`${request_uri}` e `${device_group}` exigem [Application Accelerator](/pt-br/documentacao/plataforma/applications/application-accelerator/configuracoes/) ativado na Application. Uma regra que lê uma das duas em uma Application com Application Accelerator desativado é recusada. A API responde HTTP `400` com o código de erro `25047`, `Missing Required Modules`, e a seção Erros traz o corpo completo. `${uri}` não exige nenhum recurso da plataforma, então é a variável de URI para uma Application sem Application Accelerator. Seis linhas nomeiam um padrão, e não uma variável. Em `${arg_name}`, `${cookie_name}`, `${http_name}`, `${sent_http_name}`, `${upstream_cookie_name}` e `${upstream_http_name}`, substitua `name` pelo argumento, pelo cookie ou pelo header a ser lido. @@ -76,7 +91,7 @@ Seis linhas nomeiam um padrão, e não uma variável. Em `${arg_name}`, `${cooki | `${args}` | Todos os nomes e valores de argumentos da query string | `${args}` contém `search=test` para `/path?search=test` | Request, Response | | `${cookie_name}` | O valor do cookie `name`. Troque cada hífen de `name` por um underscore | `${cookie_icl_current_language}` contém `pt-br` para `icl_current_language = pt-br` | Request, Response | | `${device_group}` | O nome do [device group](/pt-br/documentacao/plataforma/applications/device-groups/) ao qual a requisição corresponde, entre os device groups da Application. Exige Application Accelerator | `Mobile` | Request, Response | -| `${domain}` | O host name ou o header `Host` da requisição, como `${host}` o lê, sem o último subdomínio depois do domínio de segundo nível | `blog.domain.com` para `az.blog.domain.com` | Request, Response | +| `${domain}` | O host name ou o header `Host` da requisição, como `${host}` o lê, sem o último subdomínio depois do domínio de segundo nível | `blog.example.com` para `az.blog.example.com` | Request, Response | | `${geoip_city}` | O nome da cidade | `Frankfurt am Main` | Request, Response | | `${geoip_city_continent_code}` | O código de duas letras do continente | `EU`, para Europa | Request, Response | | `${geoip_city_country_code}` | O código de duas letras do país | `IN`, para Índia | Request, Response | @@ -86,9 +101,9 @@ Seis linhas nomeiam um padrão, e não uma variável. Em `${arg_name}`, `${cooki | `${geoip_country_name}` | O nome do país | `France` | Request, Response | | `${geoip_region}` | O código de duas letras da região | `FL`, para Flórida | Request, Response | | `${geoip_region_name}` | O nome da região | `Ontario` | Request, Response | -| `${host}` | Em ordem de precedência: o host name na linha da requisição, o valor do header `Host` ou o nome do servidor que atende a requisição | `blog.domain.com` | Request, Response | +| `${host}` | Em ordem de precedência: o host name na linha da requisição, o valor do header `Host` ou o nome do servidor que atende a requisição | `blog.example.com` | Request, Response | | `${http_name}` | O valor do header de requisição `name`. Escreva `name` em letras minúsculas e substitua cada hífen por um underscore. `name` precisa ser um [header de requisição HTTP](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) válido | `${http_accept}` contém `image/webp,image/apng` para `Accept: image/webp,image/apng` | Request, Response | -| `${remote_addr}` | O endereço IP do cliente que envia a requisição | `200.10.2.50` | Request, Response | +| `${remote_addr}` | O endereço IP do cliente que envia a requisição | `203.0.113.50` | Request, Response | | `${remote_port}` | A porta TCP de origem da conexão do cliente, que muda de uma conexão para outra | `6742` | Request, Response | | `${remote_user}` | O nome de usuário enviado por autenticação básica, quando a requisição carrega um | `username` | Request, Response | | `${request}` | A primeira linha da requisição como o cliente a enviou: o método, a URI e a versão HTTP | `GET /path HTTP/2.0` | Request, Response | @@ -97,15 +112,15 @@ Seis linhas nomeiam um padrão, e não uma variável. Em `${arg_name}`, `${cooki | `${request_uri}` | A URI completa da requisição, com a query string, e com os caracteres UTF-8 especiais codificados para URL. Exige Application Accelerator | `/path?var=value%20of%20var` | Request, Response | | `${scheme}` | O esquema da requisição | `https` | Request, Response | | `${sent_http_name}` | O valor do header de resposta `name`. Escreva `name` em letras minúsculas e substitua cada hífen por um underscore | `${sent_http_content_length}` contém `9593` para `Content-Length: 9593` | Response | -| `${server_addr}` | O endereço IP do servidor que recebe a requisição | `200.0.0.0` | Request | +| `${server_addr}` | O endereço IP do servidor que recebe a requisição | `198.51.100.10` | Request | | `${server_port}` | A porta do servidor que recebe a requisição | `8080` | Request | | `${status}` | O status code da resposta | `200` | Response | | `${tcpinfo_rtt}` | O round-trip time (RTT) da conexão TCP do cliente, em microssegundos | `24763` | Response | -| `${upstream_addr}` | O endereço IP e a porta da origem que respondeu. Várias origens são separadas por vírgulas. Depois de um redirecionamento interno de um grupo de servidores para outro, iniciado por um `X-Accel-Redirect` ou por uma página de erro, os grupos são separados por dois pontos | `192.168.1.1:80, 192.168.1.2:80`, ou `192.168.1.1:80, 192.168.1.2:80 : 192.168.10.1:80, 192.168.10.2:80` depois de um redirecionamento | Response | +| `${upstream_addr}` | O endereço IP e a porta da origem que respondeu. Várias origens são separadas por vírgulas. Depois de um redirecionamento interno de um grupo de servidores para outro, iniciado por um `X-Accel-Redirect` ou por uma página de erro, os grupos são separados por dois pontos | `192.0.2.1:80, 192.0.2.2:80`, ou `192.0.2.1:80, 192.0.2.2:80 : 192.0.2.11:80, 192.0.2.12:80` depois de um redirecionamento | Response | | `${upstream_cookie_name}` | O valor do cookie `name` que a origem envia em `Set-Cookie`. Quando várias origens respondem a uma requisição, somente os cookies da última são mantidos | `${upstream_cookie_uuid}` contém `12345` para `Set-Cookie: uuid = 12345` | Response | | `${upstream_http_name}` | O valor do header `name` que a origem envia. Escreva `name` em letras minúsculas e substitua cada hífen por um underscore. Quando várias origens respondem a uma requisição, somente os headers da última são mantidos | `${upstream_http_server}` contém `UploadServer` para `Server: UploadServer` | Response | | `${upstream_status}` | O status code que a origem retorna. Várias origens são separadas por vírgulas, e os grupos de um redirecionamento interno, por dois pontos, como em `${upstream_addr}` | `200, 201`, ou `500, 502 : 200, 200` depois de um redirecionamento | Response | -| `${uri}` | A URI normalizada da requisição, com a codificação de URL decodificada. O valor pode mudar enquanto a requisição é processada, por exemplo depois de um redirecionamento interno ou quando um arquivo de índice responde. Para a query string ou para caracteres codificados para URL, leia `${request_uri}` | `/path/my file.txt` | Request, Response | +| `${uri}` | A URI normalizada da requisição, com a codificação de URL decodificada e sem a query string. O valor pode mudar enquanto a requisição é processada, por exemplo depois de um redirecionamento interno ou quando um arquivo de índice responde. Para a query string ou para caracteres codificados para URL, leia `${request_uri}` | `/path/my file.txt` | Request, Response | ### Variáveis de Mutual Transport Layer Security (mTLS) @@ -116,7 +131,7 @@ Estas variáveis contêm o certificado de cliente que uma requisição apresenta | `${ssl_client_cert}` | O certificado de cliente no formato Privacy-Enhanced Mail (PEM). Descontinuada: leia `${ssl_client_escaped_cert}` em vez dela | `-----BEGIN CERTIFICATE-----` `MIICnz...` `-----END CERTIFICATE-----` | | `${ssl_client_escaped_cert}` | O certificado de cliente no formato PEM, como uma string codificada para URL | `-----BEGIN%20CERTIFICATE-----%0AMIICnz...%0A-----END%20CERTIFICATE-----` | | `${ssl_client_fingerprint}` | O fingerprint Secure Hash Algorithm 1 (SHA-1) do certificado de cliente | `2fd4e1c67a2d28fced849` | -| `${ssl_client_i_dn}` | A string do issuer Distinguished Name (DN) do certificado de cliente | `/C=US/ST=California/L=San Francisco/O=Example CA/CN=issuer.com` | +| `${ssl_client_i_dn}` | A string do issuer Distinguished Name (DN) do certificado de cliente | `/C=US/ST=California/L=San Francisco/O=Example CA/CN=issuer.example.com` | | `${ssl_client_s_dn}` | A string do subject DN do certificado de cliente | `/C=US/ST=California/L=San Francisco/O=Example CA/CN=example.com` | | `${ssl_client_s_dn_parsed}` | O subject Common Name (CN) extraído do certificado de cliente, como string | `example.com` | | `${ssl_client_serial}` | O número de série do certificado de cliente | `6C:0A:83:7E:92:3B:D6:C6:E3:56:50:E7` | @@ -135,24 +150,24 @@ Esta regra da Response Phase define um cookie que registra o host da requisiçã | | Variável | Operador | Argumento | | --- | --- | --- | --- | -| If | `${host}` | `is_equal` | `host.com` | +| If | `${host}` | `is_equal` | `example.com` | | | Behavior | Argumento | | --- | --- | --- | | Then | _Add Response Cookie_ | `cookie-host-value=${host}` | -Quando a regra corresponde, a resposta carrega `Set-Cookie: cookie-host-value=host.com`. +Quando a regra corresponde, a resposta carrega `Set-Cookie: cookie-host-value=example.com`. Outras duas variáveis agem como funções: cada uma recebe um argumento, e as duas funcionam somente dentro do argumento de um behavior. | Variável | O que retorna | Exemplo | | --- | --- | --- | -| `${cookie_time_offset(number)}` | A data atual mais um offset de `number` segundos, para a expiração de um cookie | `cookie-name=cookie-value; Expires=${cookie_time_offset(3600)}` em [Add Response Cookie](#add-request-cookie-e-add-response-cookie) faz o cookie expirar 1 hora depois de ser criado | +| `${cookie_time_offset(number)}` | A data atual mais um offset de `number` segundos, para a expiração de um cookie | `cookie-name=cookie-value; Expires=${cookie_time_offset(3600)}` em [Add Response Cookie](/pt-br/documentacao/plataforma/applications/rules-engine/#add-request-cookie-e-add-response-cookie) faz o cookie expirar 1 hora depois de ser criado | | `${encode_base64(string)}` | `string`, codificada em base64 | `${encode_base64(http://www.yourdomain.com/)}` retorna `aHR0cDovL3d3dy55b3VyZG9tYWluLmNvbS8=` | ### Operadores -Um critério compara a sua variável com o seu argumento por meio de um operador, e a API envia o operador como um destes valores em `operator`. +Um critério compara a variável com o argumento por meio de um operador, e a API envia o operador em `operator`, com um destes valores. | Operador | O critério corresponde quando | Argumento | | --- | --- | --- | @@ -198,7 +213,7 @@ As duas colunas de API indicam o `type` que cada fase aceita, e a coluna Exige i | Deliver | `deliver` | `deliver` | Nenhum | | Deny (403 Forbidden) | `deny` | Não disponível | Nenhum | | Enable Gzip | `enable_gzip` | `enable_gzip` | Nenhum | -| Enforce HLS cache | Adicionado pela Azion | Não disponível | Live Ingest | +| Enforce HLS cache | Adicionado pela Azion | Não disponível | [Live Ingest](/pt-br/documentacao/plataforma/connectors/live-ingest/) | | Filter Request Cookie / Filter Response Cookie | `filter_request_cookie` | `filter_response_cookie` | Application Accelerator | | Filter Request Header / Filter Response Header | `filter_request_header` | `filter_response_header` | Nenhum | | Finish Request Phase | `finish_request_phase` | Não disponível | Nenhum | @@ -222,7 +237,7 @@ Na Response Phase, o argumento pode carregar atributos de [Set-Cookie](https://d - `Expires=date`, no formato `EEE, d MMM yyyy HH:mm:ss Z` - `Domain=domain-value` - `Path=path-value` -- `Max-age=number`, um TTL em segundos que tem precedência sobre `Expires` +- `Max-age=number`, um time to live (TTL) em segundos que tem precedência sobre `Expires` - `SameSite=value; Secure` - `HttpOnly` @@ -288,7 +303,7 @@ _Enable Gzip_ comprime o conteúdo com gzip quando o navegador do usuário ofere ### Enforce HLS cache -_Enforce HLS cache_ impõe a política de cache que a Azion define para transmissões HLS ao vivo, e exige Live Ingest. A Azion adiciona o behavior a uma regra da Request Phase toda vez que você seleciona uma fonte Live Ingest. O behavior faz duas coisas: ignora as regras de cache da Application e aplica a política de HLS ao vivo. +_Enforce HLS cache_ impõe a política de cache que a Azion define para transmissões ao vivo por HTTP Live Streaming (HLS), e exige Live Ingest. A Azion adiciona o behavior a uma regra da Request Phase toda vez que você seleciona uma fonte Live Ingest. O behavior faz duas coisas: ignora as regras de cache da Application e aplica a política de HLS ao vivo. | Objeto | Tempo de cache | | --- | --- | @@ -317,11 +332,15 @@ Cinco headers não podem ser filtrados nem sobrescritos: ### Finish Request Phase -_Finish Request Phase_ encerra a Request Phase. Os behaviors depois dele na regra, e as regras depois dessa regra, não são executados. Ele é executado na Request Phase, não exige nenhum recurso da plataforma e é `{ "type": "finish_request_phase" }` na API. Azion Console não o oferece na lista de behaviors: envie-o pela API, ou a partir do mesmo JSON com `azion create rules-engine` na Azion CLI. +_Finish Request Phase_ encerra a Request Phase. Os behaviors depois dele na regra, e as regras depois dessa regra, não são executados. Ele é executado na Request Phase, não exige nenhum recurso da plataforma e é `{ "type": "finish_request_phase" }` na API. Azion Console não o oferece na lista de behaviors: envie-o pela API, ou a partir de um arquivo JSON com `azion create rules-engine` na Azion CLI. ### Forward Cookies -_Forward Cookies_ faz a Azion encaminhar aos usuários o header `Set-Cookie` que a origem retorna, mesmo quando a resposta vem do cache. Ele é executado na Request Phase, exige Application Accelerator ativado na Application e é `{ "type": "forward_cookies" }` na API. Uma resposta em cache pode então carregar o `Set-Cookie` da sessão de outro usuário. Para manter as sessões separadas, consulte [Encaminhe cookies da origem ao usuário](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/cache-settings/#encaminhe-cookies-da-origem-ao-usuario). +_Forward Cookies_ faz a Azion encaminhar aos usuários o header `Set-Cookie` que a origem retorna, mesmo quando a resposta vem do cache. Ele é executado na Request Phase, exige Application Accelerator ativado na Application e é `{ "type": "forward_cookies" }` na API. + +:::caution[Atenção] +Com Forward Cookies, uma resposta em cache pode carregar o `Set-Cookie` da sessão de outro usuário. Para manter as sessões separadas, consulte [Encaminhe cookies da origem ao usuário](/pt-br/documentacao/guias/performance-e-confiabilidade/cache-e-purge/cache-settings/#encaminhe-cookies-da-origem-ao-usuario). +::: A Azion não filtra o header de requisição `Cookie` por padrão, qualquer que seja a configuração de Forward Cookies, então os cookies que um script define com `document.cookie` chegam à origem. @@ -368,11 +387,13 @@ Na API, `attributes.value` contém o ID da Function Instance, e não o da Functi _Set Cache Policy_ aplica um [cache setting](/pt-br/documentacao/plataforma/applications/cache/cache-settings/) às requisições que correspondem à regra, e é assim que um cache setting chega a uma requisição. Ele é executado na Request Phase e não exige nenhum outro recurso da plataforma. O cache setting precisa existir antes que uma regra possa aplicá-lo, e [Primeiros passos com Cache](/pt-br/documentacao/plataforma/applications/cache/primeiros-passos/) cria um primeiro cache setting e a regra que o aplica. -O cache setting define por quanto tempo um objeto fica em cache. Os seus [campos de Application Accelerator](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#application-accelerator) contêm as variações que definem a cache key. Na API, `attributes.value` contém o ID do cache setting. A API retorna esse ID como um inteiro, mesmo quando a requisição o envia como string. Um cache setting que uma regra aplica não pode ser excluído: a API responde `400` com o código `21014`. +O cache setting define por quanto tempo um objeto fica em cache. Os seus [campos de Application Accelerator](/pt-br/documentacao/plataforma/applications/cache/cache-settings/#application-accelerator) contêm as variações que definem a cache key. + +Na API, `attributes.value` contém o ID do cache setting. A API retorna esse ID como um inteiro, mesmo quando a requisição o envia como string. Um cache setting que uma regra aplica não pode ser excluído: a API responde `400` com o código `21014`. ### Set Connector -_Set Connector_ envia as requisições que correspondem à regra a um [Connector](/pt-br/documentacao/plataforma/connectors/), que as encaminha à origem. Ele é executado na Request Phase e não exige nenhum recurso da plataforma, então uma regra com `${uri}` e _Set Connector_ funciona em uma Application sem Application Accelerator. Na API, `attributes.value` contém o ID do Connector, como mostra a seção API. +_Set Connector_ envia as requisições que correspondem à regra a um [Connector](/pt-br/documentacao/plataforma/connectors/), que guarda o endereço da sua origem e as encaminha a ela. Ele é executado na Request Phase e não exige nenhum recurso da plataforma, então uma regra com `${uri}` e _Set Connector_ funciona em uma Application sem Application Accelerator. Na API, `attributes.value` contém o ID do Connector, como mostra a seção API. --- @@ -384,15 +405,15 @@ Toda operação de regra é autenticada e fica em `https://api.azion.com/v4/work | --- | --- | --- | | Criar uma regra | `POST /request_rules` | `POST /response_rules` | | Listar as regras da fase | `GET /request_rules` | `GET /response_rules` | -| Consultar uma regra | `GET /request_rules/{request_rule_id}` | `GET /response_rules/{response_rule_id}` | -| Substituir uma regra | `PUT /request_rules/{request_rule_id}` | `PUT /response_rules/{response_rule_id}` | -| Atualizar parte de uma regra | `PATCH /request_rules/{request_rule_id}` | `PATCH /response_rules/{response_rule_id}` | -| Excluir uma regra | `DELETE /request_rules/{request_rule_id}` | `DELETE /response_rules/{response_rule_id}` | +| Consultar uma regra | `GET /request_rules/` | `GET /response_rules/` | +| Substituir uma regra | `PUT /request_rules/` | `PUT /response_rules/` | +| Atualizar parte de uma regra | `PATCH /request_rules/` | `PATCH /response_rules/` | +| Excluir uma regra | `DELETE /request_rules/` | `DELETE /response_rules/` | | Reordenar as regras | `PUT /request_rules/order` | `PUT /response_rules/order` | Uma criação responde `202` com um `state` igual a `pending`, e uma listagem responde `200`. A chamada de reordenação recebe um array `order` que lista os IDs das regras da fase na nova ordem. -Esta chamada cria uma regra da Request Phase que envia toda requisição da Application a um Connector: +Todo path começa com `/`, então um critério com `starts_with` e `/` corresponde a toda requisição. Esta chamada cria uma regra da Request Phase que envia toda requisição da Application a um Connector: ```bash curl --request POST \ @@ -403,8 +424,24 @@ curl --request POST \ --data '{ "name": "send-to-connector", "active": true, - "criteria": [[{ "variable": "${uri}", "conditional": "if", "operator": "starts_with", "argument": "/" }]], - "behaviors": [{ "type": "set_connector", "attributes": { "value": } }] + "criteria": [ + [ + { + "variable": "${uri}", + "conditional": "if", + "operator": "starts_with", + "argument": "/" + } + ] + ], + "behaviors": [ + { + "type": "set_connector", + "attributes": { + "value": + } + } + ] }' ``` @@ -414,13 +451,15 @@ A resposta carrega `202` e um `state` igual a `pending`. Este trecho mantém a r {"state":"pending","data":{"id":,"name":"send-to-connector","active":true,"criteria":[[{"conditional":"if","variable":"${uri}","operator":"starts_with","argument":"/"}]],"behaviors":[{"type":"set_connector","attributes":{"value":}}],"description":"","order":0,…}} ``` -A plataforma adiciona `description`, uma string vazia quando a criação não envia nenhuma, e `order`, a posição da regra na sua fase. O mesmo corpo com `${request_uri}` no lugar de `${uri}` falha com o código `25047` em uma Application sem Application Accelerator. +A plataforma adiciona `description`, uma string vazia quando a criação não envia nenhuma, e `order`, a posição da regra na sua fase. O mesmo corpo com `${request_uri}` no lugar de `${uri}` falha com o código `25047` em uma Application sem Application Accelerator. [Primeiros passos com Applications](/pt-br/documentacao/plataforma/applications/primeiros-passos/) monta a mesma regra no Azion Console. --- ## CLI -[Azion CLI](/pt-br/documentacao/devtools/cli/) cria uma regra com `azion create rules-engine`, que lê a regra de um arquivo JSON no formato que a API recebe. `--phase` indica a fase, e `azion create rules-engine` não tem padrão para ela: em um terminal, o comando pede a fase, e sem terminal ele falha com `Error: Failed to parse your response.` +[Azion CLI](/pt-br/documentacao/devtools/cli/) cria uma regra com `azion create rules-engine`, que lê a regra de um arquivo JSON no formato que a API recebe. + +A flag `--phase` indica a fase, e `azion create rules-engine` não tem padrão para ela: em um terminal, o comando pede a fase, e sem terminal ele falha com `Error: Failed to parse your response.` Este arquivo aplica um cache setting a toda requisição cujo caminho começa com `/static/`: @@ -429,8 +468,24 @@ Este arquivo aplica um cache setting a toda requisição cujo caminho começa co "name": "apply-static-assets-cache", "description": "Applies the static-assets cache setting to /static/", "active": true, - "criteria": [[{ "variable": "${uri}", "operator": "starts_with", "conditional": "if", "argument": "/static/" }]], - "behaviors": [{ "type": "set_cache_policy", "attributes": { "value": } }] + "criteria": [ + [ + { + "variable": "${uri}", + "operator": "starts_with", + "conditional": "if", + "argument": "/static/" + } + ] + ], + "behaviors": [ + { + "type": "set_cache_policy", + "attributes": { + "value": + } + } + ] } ``` diff --git a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/websocket.mdx b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/websocket.mdx index 61a2df6068..9861d43cf3 100644 --- a/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/websocket.mdx +++ b/apps/docs/src/content/docs/pt-br/pages/menu-principal/referencia/build/edge-application/websocket.mdx @@ -10,7 +10,9 @@ import FrameBox from '@aziontech/webkit/frame-box' import ItemList from '@aziontech/webkit/item-list' import DocItem from '@aziontech/webkit/doc-item' -WebSocket é um protocolo, especificado na [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455), que mantém uma conexão TCP aberta nos dois sentidos entre um cliente e um servidor. Depois de um handshake, os dois lados trocam dados por ela em tempo real. **WebSocket Proxy** é uma feature de Applications que transporta essa conexão entre os seus usuários e a sua origem. A conexão passa por uma [Application](/pt-br/documentacao/plataforma/applications/) que atua como proxy reverso para essa origem. Use WebSocket Proxy para aplicações em tempo real, como jogos online, chat, notificações e streaming ao vivo. +WebSocket é um protocolo, especificado na [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455), que mantém uma conexão TCP aberta nos dois sentidos entre um cliente e um servidor. Depois de um handshake, os dois lados trocam dados por ela em tempo real. + +**WebSocket Proxy** é uma feature de Applications que transporta essa conexão entre os seus usuários e a sua origem. A conexão passa por uma [Application](/pt-br/documentacao/plataforma/applications/) que atua como proxy reverso para essa origem. Use WebSocket Proxy para aplicações em tempo real, como jogos online, chat, notificações e streaming ao vivo. WebSocket Proxy serve quando o servidor WebSocket é a sua origem, porque a Application apenas transporta a conexão até ela. Quando uma [Function](/pt-br/documentacao/plataforma/functions/) deve agir ela mesma como servidor ou cliente WebSocket, use a [WebSocket API](/pt-br/documentacao/devtools/runtime/api-reference/websocket/), que trata um upgrade do lado do servidor com `upgradeWebSocket()`. @@ -22,7 +24,7 @@ A Azion ativa WebSocket Proxy em uma conta somente mediante solicitação. Para ## Suporte no cliente e na origem -Uma conexão WebSocket por meio de uma Application precisa de suporte nativo a WebSocket nas duas pontas: o cliente que abre a conexão e o servidor na origem. A maioria dos navegadores oferece suporte nativo a WebSocket. Para a lista de navegadores com suporte nativo, consulte [Can I use](https://caniuse.com/websockets). +Uma conexão WebSocket pela Application exige suporte nativo nas duas pontas: o cliente que abre a conexão e o servidor na origem. A maioria dos navegadores oferece suporte nativo a WebSocket. Para a lista de navegadores com suporte nativo, consulte [Can I use](https://caniuse.com/websockets). ## Headers de upgrade @@ -47,13 +49,11 @@ Uma conexão WebSocket por meio de uma Application se completa com `101 Switchin | --- | --- | --- | | Qualquer status diferente de `101` | O cliente, a Application ou a origem não completou a conexão WebSocket | Verifique o cliente, a origem e os [headers de upgrade](/pt-br/documentacao/plataforma/applications/websocket/#headers-de-upgrade) | -O cliente e a origem precisam de suporte nativo a WebSocket, e a requisição precisa dos dois headers de upgrade com os seus valores. - --- ## Limites -A Azion recicla as conexões keepalive nos seus servidores aproximadamente a cada 15 minutos, e pode encerrar uma conexão WebSocket ativa que fique aberta além desse tempo. A sua aplicação então precisa detectar a conexão encerrada e restabelecê-la. Para o tempo máximo de uma conexão WebSocket, e para saber como solicitar um limite maior para o seu plano, consulte [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/). +A Azion recicla as conexões keepalive nos seus servidores aproximadamente a cada 15 minutos. Ela pode encerrar uma conexão WebSocket ativa que fique aberta além desse tempo. A sua aplicação então precisa detectar a conexão encerrada e restabelecê-la. Para o tempo máximo de uma conexão WebSocket, e para saber como solicitar um limite maior para o seu plano, consulte [Limites de Applications](/pt-br/documentacao/plataforma/applications/limites/). ---