docs: added idempotency key documentation (#4039)

This commit is contained in:
Shahed Nasser
2023-05-08 19:21:07 +03:00
committed by GitHub
parent e9ca647a1d
commit a8887cd02f
22 changed files with 290 additions and 64 deletions

View File

@@ -0,0 +1,72 @@
---
description: "Learn what an idempotency key is in Medusa. An Idempotency Key is a unique key associated with an operation that allows you to safely retry requests."
---
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Idempotency Key
In this document, you'll learn what an idempotency key is in Medusa.
## Overview
An Idempotency Key is a unique, randomly generated key associated with an operation, such as the cart completion process. The idempotency key can be passed in the header of a request to an endpoint. This allows you to safely retry requests without accidentally performing the same operation twice.
For example, if a connection error occurs while the customer is completing their cart and placing an order, you can retry from the last recovery point before the error occurred.
When an operation first starts, the idempotency key is generated using the `uuid` package's `v4` method. Then, the backend sets the following headers in the response:
```bash
Access-Control-Expose-Headers: Idempotency-Key
Idempotency-Key: <IDEM_VAL>
```
Where `<IDEM_VAL>` is the idempotency key generated.
These headers can then be passed again for subsequent retrying requests and will be available on the response of these requests as well. The value of the idempotency key remains the same across requests and responses, even if an error occurs and you retry the request.
For example, when the cart completion process starts, the Medusa backend generates the idempotency key and sets the necessary headers on the response. If an error occurs in the request, you can later retry the request by passing these same headers in your request.
---
## IdempotencyKey Entity Overview
The idempotency key's data is stored within the `IdempotencyKey` entity. Some of its attributes include:
- `idempotency_key`: a unique string indicating the value of the idempotency key.
- `request_method`: a string indicating the method of the latest request related to the idempotency key's operation. For example, `POST`.
- `request_params`: a JSONB object indicating the parameters of the latest request related to the idempotency key's operation.
- `request_path`: a string indicating the path of the latest request related to the idempotency key's operation.
- `response_code`: a number indicating the response code of the latest request related to the idempotency key's operation.
- `response_body`: a JSONB object indicating the response body of the latest request related to the idempotency key's operation.
- `recovery_point`: a string indicating the point to continue from when retrying the request. The default value is `started`.
---
## Idempotency Key Stages
Idempotency key stages are the different recovery points that are available for an operation. Every operation has at least the `started` and `finished` stages.
For example, the cart completion operation has the following stages or recovery points:
- `started`
- `tax_lines_created`
- `payment_authorized`
- `finished`
---
## Custom Development
You can use the `IdempotencyKeyService` in your custom development to ensure requests can be safely retried or continued.
<DocCard item={{
type: 'link',
href: '/development/idempotency-key/use-service',
label: 'Use IdempotencyKeyService',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to use the IdempotencyKeyService in your code.'
}
}} />

View File

@@ -0,0 +1,153 @@
---
description: 'Learn how to create a loader in Medusa. A loader can be created in the Medusa backend codebase, in a plugin, or in a module.'
addHowToData: true
---
# How to Use IdempotencyKeyService
In this document, you'll learn how to use the `IdempotencyKeyService`.
## Overview
You can use the `IdempotencyKeyService` within your custom development to ensure that your custom endpoints and operations can be safely retried or continued if an error occurs. This guide is also useful if you're overriding an existing feature in Medusa that uses the `IdempotencyKeyService` and you want to maintain its usage, such as if you're overriding the cart completion strategy.
The `IdempotencyKeyService` includes methods that can be used to create and update idempotency keys, among other functionalities.
---
## Create Idempotency Key
You can create an idempotency key within an endpoint using the `create` method of the `IdempotencyKeyService`:
```ts
router.post("/custom-route", async (req, res) => {
// ...
const idempotencyKey = await idempotencyKeyService.create({
request_method: req.method,
request_params: req.params,
request_path: req.path,
})
// ...
})
```
The method requires as a parameter an object having the following properties:
- `request_method`: a string indicating the request method to be associated with the idempotency key.
- `request_params`: an object indicating the request parameters to be associated with the idempotency key.
- `request_path`: a string indicating the request path to be associated with the idempotency key.
The method handles generating the idempotency key value and saving the idempotency key with its details in the database. It returns the full idempotency key object.
Alternativaly, you can use the `initializeRequest` method that allows you to retrieve an idempotency key based on the value passed in the `Idempotency-Key` header of the request if it exists, or create a new key otherwise. For example:
```ts
router.post("/custom-route", async (req, res) => {
// ...
const headerKey = req.get("Idempotency-Key") || ""
const idempotencyKey = await idempotencyKeyService
.initializeRequest(
headerKey,
req.method,
req.params,
req.path
)
// ...
})
```
The method requires the following parameters:
1. The first parameter is the key existing in the header of the request, if there's any.
2. The second parameter is the request's method.
3. The third parameter is the request's parameters.
4. The fourth method is the request's path.
The method returns the full idempotency key object.
---
## Perform Actions Within Idempotency Key Stages
Each [idempotency key stage](./overview.mdx#idempotency-key-stages) typically has transactions performed within it. Using the `IdempotencyKeyService`'s `workStage` method allows you to perform related functionalities in transactional isolation within each stage. You can access the stage or recovery point of an idempotency key using the `recovery_point` attribute.
The following example is taken from the `CartCompletionStrategy` implemented in the Medusa backend:
<!-- eslint-disable no-fallthrough -->
```ts
class CartCompletionStrategy
extends AbstractCartCompletionStrategy {
// ...
async complete(
id: string,
ikey: IdempotencyKey,
context: RequestContext
): Promise<CartCompletionResponse> {
// ...
let inProgress = true
let err: unknown = false
while (inProgress) {
switch (idempotencyKey.recovery_point) {
case "started": {
await this.activeManager_
.transaction(
"SERIALIZABLE",
async (transactionManager) => {
idempotencyKey =
await this.idempotencyKeyService_
.withTransaction(transactionManager)
.workStage(
idempotencyKey.idempotency_key,
async (manager) =>
await this.handleCreateTaxLines(
id,
{
manager,
}
)
)
}
)
.catch((e) => {
inProgress = false
err = e
})
break
}
case "tax_lines_created": {
// ...
}
case "payment_authorized": {
// ...
}
case "finished": {
// ...
}
default: {
// ...
}
}
}
// ...
}
}
```
The method requires the following parameters:
1. The first parameter is the idempotency key value.
2. The second parameter is a callback function to be executed. The function should return an object that is used to update the idempotency key's details. The object can include the following parameters:
1. `recovery_point`: a string indicating the new recovery point associated with the idempotency key's operation. If no `recovery_point` is returned in the object, the `finished` recovery point is assigned by default.
2. `response_code`: a number indicating the latest response code of the idempotency key's operation.
3. `response_body`: an object indicating the latest response body of the idempotency key's operation.
The method returns an updated idempotency key object.

View File

@@ -1,5 +1,5 @@
---
description: "earn what loaders are in Medusa. A loader is a script that runs when the Medusa backend starts."
description: "Learn what loaders are in Medusa. A loader is a script that runs when the Medusa backend starts."
---
import DocCard from '@theme/DocCard';

View File

@@ -90,7 +90,7 @@ The cart completion strategy is required to implement a single method: the `comp
The method accepts three parameters:
- `cartId`: the first parameter of the method, which is a string indicating the ID of the cart to complete.
- `idempotencyKey`: the second parameter of the method, which is an instance of the `IdempotencyKey` entity. The idempotency key is retrieved based on the idempotency key passed in the header of the request, and its used to determine the current point reached in the checkout flow to avoid inconsistencies on interruptions. You can learn more about the idempotency key [here](../cart.md#idempotency-key).
- `idempotencyKey`: the second parameter of the method, which is an instance of the `IdempotencyKey` entity. The idempotency key is retrieved based on the idempotency key passed in the header of the request, and its used to determine the current point reached in the checkout flow to avoid inconsistencies on interruptions. You can learn more about the idempotency key [here](../cart.md#idempotency-key). You can also learn how to use it within your strategy by following [this guide](../../../development/idempotency-key/use-service.md)
- `context`: the third parameter of the method, which is an object that holds a single property `ip`. `ip` is a string indicating the IP of the customer.
The completion strategy is expected to return an object with the following properties:

View File

@@ -67,13 +67,9 @@ You can initiate the cart completion process by sending a request to the [Comple
### Idempotency Key
An Idempotency Key is a unique key associated with a cart. It is generated when the cart completion process is started. The idempotency key is stored in the Cart entity under the attribute `idempotency_key`.
An Idempotency Key is a unique key associated with a cart. It is generated when the cart completion process is started and can be used to retry cart completion safely if an error occurs. The idempotency key is stored in the Cart entity under the attribute `idempotency_key`.
That Idempotency Key is then set in the header under the `Idempotency-Key` response header field along with the header field `Access-Control-Expose-Headers` set to `Idempotency-Key`.
The backend wraps essential parts of the checkout completion in its own step and stores the current step (known as recovery point) of checkout with its associated Idempotency Key.
Then, if the request is interrupted for any reason or an error occurs, the client can retry completing the checkout using the Idempotency Key, and the flow will continue from the last stored step.
You can learn more about idempotency keys [here](../../development/idempotency-key/overview.mdx).
### Cart Completion Process

View File

@@ -130,17 +130,11 @@ Additionally, `Payment` has the `captured_at` date-time attribute which is fille
## Idempotency Key
An Idempotency Key is a unique key associated with a cart. It is generated at the last step of checkout before authorization of the payment is attempted.
An Idempotency Key is a unique key associated with a cart. It is generated at the last step of checkout before authorization of the payment is attempted and used in the request and response header.
That Idempotency Key is then set in the header under the `Idempotency-Key` response header field along with the header field `Access-Control-Expose-Headers` set to `Idempotency-Key`.
If the request is interrupted for any reason or the payment fails, the client can retry completing the check out using the Idempotency Key, and the flow will continue from the last stored step. This prevents any payment issues from occurring with the customers and allows for secure retries of failed payments or interrupted connections.
If an error occurs or the purchase is interrupted at any step, the client can retry the payment by adding the Idempotency Key of the cart as the `Idempotency-Key` header field in their subsequent requests.
The backend wraps each essential part of the checkout completion in its own step and stores the current step of checkout with its associated Idempotency Key.
If then the request is interrupted for any reason or the payment fails, the client can retry completing the check out using the Idempotency Key, and the flow will continue from the last stored step.
This prevents any payment issues from occurring with the customers and allows for secure retries of failed payments or interrupted connections.
You can learn more about idempotency keys [here](../../development/idempotency-key/overview.mdx).
---

View File

@@ -36,13 +36,9 @@ You can create a claim either using the [Create Claim endpoint](/api/admin#tag/O
### Idempotency Key
An Idempotency Key is a unique key associated with a claim. It is generated when the claim creation process is started by the admin using the Create Claim endpoint. The idempotency key is stored in the `ClaimOrder` entity in the attribute `idempotency_key`.
An Idempotency Key is a unique key associated with a claim. It is generated when the claim creation process is started by the admin using the [Create Claim endpoint](/api/admin#tag/Orders/operation/PostOrdersOrderClaims) and can be used to retry the claim creation safely if an error occurs. The idempotency key is stored in the `ClaimOrder` entity in the attribute `idempotency_key`.
That Idempotency Key is then set in the header under the `Idempotency-Key` response header field along with the header field `Access-Control-Expose-Headers` set to `Idempotency-Key`.
The backend wraps essential parts of the claim creation process in its own step and stores the current step (known as recovery point) of the process with its associated Idempotency Key.
Then, if the request is interrupted for any reason or an error occurs, the client can retry creating the return using the Idempotency Key, and the flow will continue from the last stored step.
You can learn more about idempotency keys [here](../../development/idempotency-key/overview.mdx).
### Create Claim Endpoint Process

View File

@@ -42,13 +42,9 @@ Returns can be created in three ways:
### Idempotency Key
An Idempotency Key is a unique key associated with a return. It is generated when the return creation process is started by the customer. The idempotency key is stored in the `Return` entity in the attribute `idempotency_key`.
An Idempotency Key is a unique key associated with a return. It is generated when the return creation process is started by the customer and can be used to retry the return creation safely if an error occurs. The idempotency key is stored in the `Return` entity in the attribute `idempotency_key`.
That Idempotency Key is then set in the header under the `Idempotency-Key` response header field along with the header field `Access-Control-Expose-Headers` set to `Idempotency-Key`.
The backend wraps essential parts of the return creation process in its own step and stores the current step (known as recovery point) of the process with its associated Idempotency Key.
Then, if the request is interrupted for any reason or an error occurs, the client can retry creating the return using the Idempotency Key, and the flow will continue from the last stored step.
You can learn more about idempotency keys [here](../../development/idempotency-key/overview.mdx).
### Return Creation Process Through the Customer

View File

@@ -39,16 +39,12 @@ In Medusa, Swaps are created by the customer through the storefront. This ensure
### Idempotency Key
An Idempotency Key is a unique key associated with a swap. It is generated when the swap creation process is started. The idempotency key is stored in the `Swap` entity under the attribute `idempotency_key`.
That Idempotency Key is then set in the header under the `Idempotency-Key` response header field along with the header field `Access-Control-Expose-Headers` set to `Idempotency-Key`.
The backend wraps essential parts of the swap creation process in its own step and stores the current step (known as recovery point) of the process with its associated Idempotency Key.
Then, if the request is interrupted for any reason or an error occurs, the client can retry creating the swap using the Idempotency Key, and the flow will continue from the last stored step.
An Idempotency Key is a unique key associated with a swap. It is generated when the swap creation process is started and can be used to retry the swap creation safely if an error occurs. The idempotency key is stored in the `Swap` entity under the attribute `idempotency_key`.
Keep in mind that the idempotency key stored in the swap is only used when creating the swap. All operations related to the swaps cart and its completion use the [carts idempotency key](../carts-and-checkout/cart.md#idempotency-key).
You can learn more about idempotency keys [here](../../development/idempotency-key/overview.mdx).
### Swap Creation Process
The customer starts by creating their swap, which can be done through the Create Swap endpoint. In this endpoint, the following steps are implemented:

View File

@@ -129,7 +129,7 @@
* nullable: true
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
* context:
* description: "The context of the cart which can include info like IP or user agent."

View File

@@ -262,6 +262,6 @@ export class ClaimOrder extends SoftDeletableEntity {
* nullable: true
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
*/

View File

@@ -151,7 +151,7 @@ export class DraftOrder extends BaseEntity {
* nullable: true
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
* created_at:
* description: The date with timezone at which the resource was created.

View File

@@ -199,7 +199,7 @@ export class Fulfillment extends BaseEntity {
* nullable: true
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
* created_at:
* description: The date with timezone at which the resource was created.

View File

@@ -74,7 +74,7 @@ export class IdempotencyKey {
* description: The unique randomly generated key used to determine the state of a process.
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
* created_at:
* description: Date which the idempotency key was locked.

View File

@@ -487,7 +487,7 @@ export class Order extends BaseEntity {
* nullable: true
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
* external_id:
* description: The ID of an external order.

View File

@@ -132,7 +132,7 @@ export class PaymentSession extends BaseEntity {
* nullable: true
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
* amount:
* description: The amount that the Payment Session has been authorized for.

View File

@@ -181,7 +181,7 @@ export class Payment extends BaseEntity {
* nullable: true
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
* created_at:
* description: The date with timezone at which the resource was created.

View File

@@ -124,7 +124,7 @@ export class Refund extends BaseEntity {
* nullable: true
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
* created_at:
* description: The date with timezone at which the resource was created.

View File

@@ -191,7 +191,7 @@ export class Return extends BaseEntity {
* nullable: true
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
* received_at:
* description: The date with timezone at which the return was received.

View File

@@ -248,7 +248,7 @@ export class Swap extends SoftDeletableEntity {
* nullable: true
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
* created_at:
* description: The date with timezone at which the resource was created.

View File

@@ -74,7 +74,7 @@ export class TrackingLink extends SoftDeletableEntity {
* nullable: true
* type: string
* externalDocs:
* url: https://docs.medusajs.com/modules/carts-and-checkout/cart.md#idempotency-key
* url: https://docs.medusajs.com/development/idempotency-key/overview.md
* description: Learn more how to use the idempotency key.
* created_at:
* description: The date with timezone at which the resource was created.

View File

@@ -1283,7 +1283,7 @@ module.exports = {
items: [
{
type: "category",
label: "Entities",
label: "Entity",
items: [
{
type: "doc",
@@ -1293,7 +1293,7 @@ module.exports = {
{
type: "doc",
id: "development/entities/migrations/overview",
label: "Migrations",
label: "Migration",
},
{
type: "ref",
@@ -1331,7 +1331,7 @@ module.exports = {
},
{
type: "category",
label: "Endpoints",
label: "Endpoint",
items: [
{
type: "doc",
@@ -1353,7 +1353,7 @@ module.exports = {
{
type: "doc",
id: "development/endpoints/add-middleware",
label: "Middlewares",
label: "Middleware",
},
{
type: "doc",
@@ -1364,7 +1364,7 @@ module.exports = {
},
{
type: "category",
label: "Services",
label: "Service",
items: [
{
type: "doc",
@@ -1397,7 +1397,7 @@ module.exports = {
},
{
type: "category",
label: "Events",
label: "Event",
items: [
{
type: "doc",
@@ -1407,7 +1407,7 @@ module.exports = {
{
type: "doc",
id: "development/events/subscribers",
label: "Subscribers",
label: "Subscriber",
},
{
type: "doc",
@@ -1452,7 +1452,7 @@ module.exports = {
},
{
type: "category",
label: "Loaders",
label: "Loader",
items: [
{
type: "doc",
@@ -1475,7 +1475,7 @@ module.exports = {
},
{
type: "category",
label: "Scheduled Jobs",
label: "Scheduled Job",
items: [
{
type: "doc",
@@ -1498,7 +1498,7 @@ module.exports = {
},
{
type: "category",
label: "Modules",
label: "Module",
items: [
{
type: "doc",
@@ -1526,7 +1526,7 @@ module.exports = {
},
{
type: "category",
label: "Plugins",
label: "Plugin",
items: [
{
type: "doc",
@@ -1604,7 +1604,7 @@ module.exports = {
},
{
type: "category",
label: "Publishable API Keys",
label: "Publishable API Key",
items: [
{
type: "doc",
@@ -1632,7 +1632,7 @@ module.exports = {
},
{
type: "category",
label: "Notifications",
label: "Notification",
items: [
{
type: "doc",
@@ -1701,7 +1701,30 @@ module.exports = {
},
{
type: "category",
label: "Batch Jobs",
label: "Idempotency Key",
items: [
{
type: "doc",
id: "development/idempotency-key/overview",
label: "Overview",
},
{
type: "html",
value: "How-to",
customProps: {
sidebar_is_group_divider: true,
},
},
{
type: "doc",
id: "development/idempotency-key/use-service",
label: "Use IdempotencyKeyService",
},
],
},
{
type: "category",
label: "Batch Job",
items: [
{
type: "doc",
@@ -1729,7 +1752,7 @@ module.exports = {
},
{
type: "category",
label: "Strategies",
label: "Strategy",
items: [
{
type: "doc",
@@ -1752,7 +1775,7 @@ module.exports = {
},
{
type: "category",
label: "Feature Flags",
label: "Feature Flag",
items: [
{
type: "doc",