Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(medusa): Improve add line item to cart perf and transaction management + clustering start command #5701

Merged
merged 43 commits into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
dc2593b
[WIP]
adrien2p Nov 23, 2023
f85e7c9
wip
adrien2p Nov 23, 2023
ba56119
wip
adrien2p Nov 23, 2023
682c491
WIP
adrien2p Nov 23, 2023
3d1bb7d
fix tests
adrien2p Nov 23, 2023
53bd841
WIP
adrien2p Nov 23, 2023
59cd15e
Merge branch 'develop' into feat/improve-create-line-item-end-point
adrien2p Nov 23, 2023
a7377a8
feat: start-cluster cli
carlos-r-l-rodrigues Nov 23, 2023
be18f99
Merge branch 'feat/improve-create-line-item-end-point' of https://git…
carlos-r-l-rodrigues Nov 23, 2023
b056b90
feat: config number of cpus
carlos-r-l-rodrigues Nov 23, 2023
4e22739
fix idem
adrien2p Nov 23, 2023
0d7bea0
fix step
adrien2p Nov 23, 2023
ed316a4
Merge branch 'develop' into feat/improve-create-line-item-end-point
adrien2p Nov 23, 2023
f34f622
Create tasty-ants-visit.md
adrien2p Nov 23, 2023
d68faa7
process.env.MEDUSA_ADMIN_UI_SKIP_CACHE
carlos-r-l-rodrigues Nov 23, 2023
0be0e15
rename var
carlos-r-l-rodrigues Nov 23, 2023
0e376bd
finish
adrien2p Nov 23, 2023
7c987a8
Merge branch 'feat/improve-create-line-item-end-point' of github.com:…
adrien2p Nov 23, 2023
058ea4d
chore: admin ui skip copy
carlos-r-l-rodrigues Nov 23, 2023
8a1b99a
Merge branch 'feat/improve-create-line-item-end-point' of https://git…
carlos-r-l-rodrigues Nov 23, 2023
9157b49
chore: move ping
carlos-r-l-rodrigues Nov 23, 2023
9546768
finalise
adrien2p Nov 24, 2023
548b0ee
fix service usage
adrien2p Nov 24, 2023
7fc5c72
fix unit tests
adrien2p Nov 24, 2023
7c9511e
fix tests
adrien2p Nov 24, 2023
fa94de8
Merge branch 'develop' into feat/improve-create-line-item-end-point
adrien2p Nov 24, 2023
2999256
cleanup
adrien2p Nov 24, 2023
a949e18
update changeset
adrien2p Nov 24, 2023
2aefc24
Merge branch 'feat/improve-create-line-item-end-point' of github.com:…
adrien2p Nov 24, 2023
6c49940
Merge branch 'develop' into feat/improve-create-line-item-end-point
adrien2p Nov 24, 2023
9f2eefd
fix unit tests
adrien2p Nov 24, 2023
9decfa4
Merge branch 'feat/improve-create-line-item-end-point' of github.com:…
adrien2p Nov 24, 2023
31cca54
Merge branch 'develop' into feat/improve-create-line-item-end-point
carlos-r-l-rodrigues Nov 24, 2023
db621a9
await promises
adrien2p Nov 24, 2023
929b76c
Merge branch 'feat/improve-create-line-item-end-point' of github.com:…
adrien2p Nov 24, 2023
21f3987
address minor
adrien2p Nov 27, 2023
484efd5
Address pr feedback
adrien2p Dec 1, 2023
fc3cb25
missing await
adrien2p Dec 1, 2023
92d3e6f
fix check
adrien2p Dec 1, 2023
f78471e
fix check
adrien2p Dec 1, 2023
ac856f1
fix integration
adrien2p Dec 4, 2023
1c6fc68
remove unnecessary import to non existing function anymore
adrien2p Dec 4, 2023
304c3ad
Merge branch 'develop' into feat/improve-create-line-item-end-point
adrien2p Dec 4, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/tasty-ants-visit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@medusajs/medusa": patch
"@medusajs/medusa-cli": patch
"@medusajs/admin-ui": patch
---

feat(medusa, medusa-cli): Improve add line item + cluster starting with medusa cli
20 changes: 8 additions & 12 deletions integration-tests/helpers/draft-order-seeder.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,27 +145,23 @@ module.exports = async (dataSource, data = {}) => {
name: "Test Region",
currency_code: "usd",
tax_rate: 0,
payment_providers: [
{
id: "test-pay",
is_installed: true,
},
],
})

await manager.query(
`insert into region_payment_providers values ('test-region', 'test-pay');`
)

await manager.insert(Region, {
id: "test-region-2",
name: "Test Region 2",
currency_code: "eur",
tax_rate: 0,
payment_providers: [
{
id: "test-pay",
is_installed: true,
},
],
})

await manager.query(
`insert into region_payment_providers values ('test-region-2', 'test-pay');`
)

await manager.insert(DiscountRule, {
id: "discount_rule_id",
description: "test description",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const {
getContainer,
} = require("../../../../environment-helpers/use-container")

jest.setTimeout(30000)
jest.setTimeout(60000)

const adminHeaders = { headers: { "x-medusa-access-token": "test_token" } }

Expand Down
4 changes: 3 additions & 1 deletion packages/admin-ui/src/node/actions/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ export async function build({
options,
reporting = "fancy",
}: BuildArgs) {
await createCacheDir({ appDir, plugins })
if (!process.env.PLUGIN_ADMIN_UI_SKIP_CACHE) {
await createCacheDir({ appDir, plugins })
}

const cacheDir = path.resolve(appDir, ".cache")
const entry = path.resolve(cacheDir, "admin", "src", "main.tsx")
Expand Down
4 changes: 4 additions & 0 deletions packages/admin-ui/src/node/utils/create-cache-dir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { createEntry } from "./create-entry"
import { logger } from "./logger"

async function copyAdmin(dest: string) {
if (process.env.PLUGIN_ADMIN_UI_SKIP_CACHE) {
return true
}

const adminDir = path.resolve(__dirname, "..", "ui")
const destDir = path.resolve(dest, "admin")

Expand Down
4 changes: 4 additions & 0 deletions packages/admin-ui/src/node/utils/create-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import {
const FILE_EXT_REGEX = /\.[^/.]+$/

async function copyLocalExtensions(src: string, dest: string) {
if (process.env.PLUGIN_ADMIN_UI_SKIP_CACHE) {
return true
}

try {
await fse.copy(src, dest, {
filter: copyFilter,
Expand Down
44 changes: 40 additions & 4 deletions packages/medusa-cli/src/create-cli.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import path from "path"
import resolveCwd from "resolve-cwd"
import { sync as existsSync } from "fs-exists-cached"
import { setTelemetryEnabled } from "medusa-telemetry"
import path from "path"
import resolveCwd from "resolve-cwd"

import { getLocalMedusaVersion } from "./util/version"
import { didYouMean } from "./did-you-mean"
import { getLocalMedusaVersion } from "./util/version"

import reporter from "./reporter"
import { newStarter } from "./commands/new"
import reporter from "./reporter"

const yargs = require(`yargs`)

Expand Down Expand Up @@ -233,6 +233,42 @@ function buildLocalCommands(cli, isLocalProject) {
})
),
})
.command({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

comment: needs documentation

command: `start-cluster`,
desc: `Start development server in cluster mode (beta).`,
builder: (_) =>
_.option(`H`, {
alias: `host`,
type: `string`,
default: defaultHost,
describe: `Set host. Defaults to ${defaultHost}`,
})
.option(`p`, {
alias: `port`,
type: `string`,
default: process.env.PORT || defaultPort,
describe: process.env.PORT
? `Set port. Defaults to ${process.env.PORT} (set by env.PORT) (otherwise defaults ${defaultPort})`
: `Set port. Defaults to ${defaultPort}`,
})
.option(`c`, {
alias: `cpus`,
type: `number`,
default: process.env.CPUS,
describe:
"Set number of cpus to use. Defaults to max number of cpus available on the system (set by env.CPUS)",
}),
handler: handlerP(
getCommandHandler(`start-cluster`, (args, cmd) => {
process.env.NODE_ENV = process.env.NODE_ENV || `development`
cmd(args)
// Return an empty promise to prevent handlerP from exiting early.
// The development server shouldn't ever exit until the user directly
// kills it so this is fine.
return new Promise((resolve) => {})
})
),
})
.command({
command: `user`,
desc: `Create a user`,
Expand Down
106 changes: 78 additions & 28 deletions packages/medusa/src/api/routes/store/carts/create-line-item/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@ import { IsInt, IsOptional, IsString } from "class-validator"
import { EntityManager } from "typeorm"
import { validator } from "../../../../../utils/validator"
import {
addOrUpdateLineItem,
CreateLineItemSteps,
handleAddOrUpdateLineItem,
setPaymentSession,
setVariantAvailability,
} from "./utils/handler-steps"
import { IdempotencyKey } from "../../../../../models"
import {
initializeIdempotencyRequest,
runIdempotencyStep,
RunIdempotencyStepOptions,
} from "../../../../../utils/idempotency"
import { initializeIdempotencyRequest } from "../../../../../utils/idempotency"
import { cleanResponseData } from "../../../../../utils/clean-response-data"
import IdempotencyKeyService from "../../../../../services/idempotency-key"
import { defaultStoreCartFields, defaultStoreCartRelations } from "../index"
import { CartService } from "../../../../../services"
import { promiseAll } from "@medusajs/utils"

/**
* @oas [post] /store/carts/{id}/line-items
Expand Down Expand Up @@ -89,34 +91,82 @@ export default async (req, res) => {
let inProgress = true
let err: unknown = false

const stepOptions: RunIdempotencyStepOptions = {
manager,
idempotencyKey,
container: req.scope,
isolationLevel: "SERIALIZABLE",
}
const idempotencyKeyService: IdempotencyKeyService = req.scope.resolve(
"idempotencyKeyService"
)

while (inProgress) {
switch (idempotencyKey.recovery_point) {
case CreateLineItemSteps.STARTED: {
await runIdempotencyStep(async ({ manager }) => {
return await handleAddOrUpdateLineItem(
id,
{
customer_id: customerId,
metadata: validated.metadata,
quantity: validated.quantity,
variant_id: validated.variant_id,
},
{
manager,
container: req.scope,
}
)
}, stepOptions).catch((e) => {
try {
const cartId = id
const data = {
customer_id: customerId,
metadata: validated.metadata,
quantity: validated.quantity,
variant_id: validated.variant_id,
}

await addOrUpdateLineItem({
cartId,
container: req.scope,
manager,
data,
})

idempotencyKey = await idempotencyKeyService
.withTransaction(manager)
.update(idempotencyKey.idempotency_key, {
recovery_point: CreateLineItemSteps.SET_PAYMENT_SESSIONS,
})
} catch (e) {
inProgress = false
err = e
})
}

break
}

case CreateLineItemSteps.SET_PAYMENT_SESSIONS: {
try {
const cartService: CartService = req.scope.resolve("cartService")

const cart = await cartService
.withTransaction(manager)
.retrieveWithTotals(id, {
select: defaultStoreCartFields,
relations: [
...defaultStoreCartRelations,
"billing_address",
"region.payment_providers",
"payment_sessions",
"customer",
],
})

const args = {
cart,
container: req.scope,
manager,
}

await promiseAll([
setVariantAvailability(args),
setPaymentSession(args),
])

idempotencyKey = await idempotencyKeyService
.withTransaction(manager)
.update(idempotencyKey.idempotency_key, {
recovery_point: CreateLineItemSteps.FINISHED,
response_code: 200,
response_body: { cart },
})
} catch (e) {
inProgress = false
err = e
}

break
}

Expand Down
Loading