Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
82 changes: 25 additions & 57 deletions bun.lock

Large diffs are not rendered by default.

51 changes: 50 additions & 1 deletion server/src/internal/catalog/actions/catalogPlanDependencies.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { type CatalogPlanParams, ErrCode, RecaseError } from "@autumn/shared";
import {
type CatalogPlanParams,
ErrCode,
type FullProduct,
RecaseError,
} from "@autumn/shared";

const referenceKey = (id: string, version?: number) =>
version === undefined ? id : `${id}@${version}`;
Expand Down Expand Up @@ -36,6 +41,12 @@ export const sortCatalogPlansByDependencies = (
}
if (visited.has(key)) return;
visiting.add(key);
if (plan.version !== undefined && plan.version > 1) {
const previous = byReference.get(
referenceKey(plan.plan_id, plan.version - 1),
);
if (previous) visit(previous);
}
for (const reference of dependenciesForPlan(plan)) {
const dependency =
byReference.get(referenceKey(reference.id, reference.version)) ??
Expand All @@ -49,3 +60,41 @@ export const sortCatalogPlansByDependencies = (
for (const plan of plans) visit(plan);
return sorted;
};

export const validateCatalogPlanVersionTargets = ({
plans,
products,
}: {
plans: CatalogPlanParams[];
products: FullProduct[];
}) => {
const existing = new Set(
products.map((product) => referenceKey(product.id, product.version)),
);
const latestById = new Map<string, number>();
for (const product of products) {
latestById.set(
product.id,
Math.max(latestById.get(product.id) ?? 0, product.version),
);
}

for (const plan of sortCatalogPlansByDependencies(plans)) {
if (
plan.version === undefined ||
existing.has(referenceKey(plan.plan_id, plan.version))
) {
continue;
}
const expected = (latestById.get(plan.plan_id) ?? 0) + 1;
if (plan.version !== expected) {
throw new RecaseError({
message: `Plan ${plan.plan_id} version must be ${expected}, received ${plan.version}.`,
code: ErrCode.InvalidRequest,
statusCode: 400,
});
}
existing.add(referenceKey(plan.plan_id, plan.version));
latestById.set(plan.plan_id, plan.version);
}
};
8 changes: 6 additions & 2 deletions server/src/internal/catalog/actions/catalogPlanPreflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ import {
validatePlanLicenseUpdate,
} from "@/internal/licenses/actions/links/syncPlanLicenses.js";
import { ProductService } from "@/internal/products/ProductService.js";
import { sortCatalogPlansByDependencies } from "./catalogPlanDependencies.js";
import {
sortCatalogPlansByDependencies,
validateCatalogPlanVersionTargets,
} from "./catalogPlanDependencies.js";

const virtualProduct = ({
current,
Expand Down Expand Up @@ -49,6 +52,7 @@ const preflightCatalogLicenses = async ({
env: ctx.env,
returnAll: true,
});
validateCatalogPlanVersionTargets({ plans, products: persistedProducts });
const currentById = new Map<string, FullProduct>();
for (const product of persistedProducts) {
const current = currentById.get(product.id);
Expand All @@ -73,7 +77,7 @@ const preflightCatalogLicenses = async ({
? previews[index]?.versionable
? (latest?.version ?? current.version) + 1
: current.version
: 1,
: (plan.version ?? 1),
archived: plan.archived,
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const previewNewPlan = ({
const {
plan_id,
new_plan_id,
version: _version,
version,
variants: _variants,
include_versions: _includeVersions,
include_variants: _includeVariants,
Expand All @@ -43,7 +43,7 @@ const previewNewPlan = ({
});
const product = {
env: ctx.env,
version: 1,
version: version ?? 1,
created_at: Date.now(),
archived: false,
...resolved,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,32 @@ const upsertPlans = async ({

if (!current) {
const variantUpdates = variants ?? [];
const latest =
Comment thread
charlietlamb marked this conversation as resolved.
version === undefined
Comment thread
charlietlamb marked this conversation as resolved.
? null
: await ProductService.getFull({
db,
idOrInternalId: plan_id,
orgId: org.id,
env,
allowNotFound: true,
});
if (latest) {
const updates = apiPlan.map.paramsV1ToProductV2({
ctx,
currentFullProduct: latest,
params: { id: new_plan_id ?? plan_id, ...rest },
}) as UpdateProductV2Params;
await updateProduct({
ctx,
productId: plan_id,
query: { force_version: true },
updates,
initialFullProduct: latest,
variantUpdates,
});
continue;
}
Comment thread
charlietlamb marked this conversation as resolved.
const createParams = apiPlan.map.paramsV1ToProductV2({
ctx,
params: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,108 @@ test.concurrent(
},
);

/** Fresh explicit versions must resolve and persist same-batch pinned license versions. */
test.concurrent(
`${chalk.yellowBright("licenses: catalog creates fresh explicit versions with pinned dependencies")}`,
async () => {
const suffix = Math.random().toString(36).slice(2, 9);
const { autumnV2_2 } = await initScenario({
customerId: `license-catalog-fresh-versions-${suffix}`,
setup: [s.customer({ testClock: false })],
actions: [],
});
const parentId = `license_catalog_fresh_parent_${suffix}`;
const childId = `license_catalog_fresh_child_${suffix}`;
const plans = [
{
plan_id: childId,
version: 1,
name: "Child",
items: [
{
feature_id: TestFeature.Messages,
included: 10,
reset: { interval: "month" as const },
},
],
licenses: [],
},
{
plan_id: parentId,
version: 1,
name: "Parent",
licenses: [{ license_plan_id: childId, version: 1, included: 1 }],
},
{
plan_id: childId,
version: 2,
name: "Child",
items: [
{
feature_id: TestFeature.Messages,
included: 20,
reset: { interval: "month" as const },
},
],
licenses: [],
},
{
plan_id: parentId,
version: 2,
name: "Parent",
licenses: [{ license_plan_id: childId, version: 2, included: 2 }],
},
].reverse();

const preview = (await autumnV2_2.post("/catalog.preview_update", {
expand: ["plan_changes.plan"],
plans,
})) as CatalogPreviewUpdateResponse;
expect(preview.plan_changes).toHaveLength(4);
expect(preview.plan_changes[0]?.plan?.licenses).toEqual([
{
license_plan_id: childId,
version: 2,
included: 2,
prepaid_only: true,
},
]);

await autumnV2_2.post("/catalog.update", { plans });
const [parentV1, parentV2, childV1, childV2] = await Promise.all([
autumnV2_2.post("/plans.get", { plan_id: parentId, version: 1 }),
autumnV2_2.post("/plans.get", { plan_id: parentId, version: 2 }),
autumnV2_2.post("/plans.get", { plan_id: childId, version: 1 }),
autumnV2_2.post("/plans.get", { plan_id: childId, version: 2 }),
]);
expect([
parentV1.version,
parentV2.version,
childV1.version,
childV2.version,
]).toEqual([1, 2, 1, 2]);
expect(childV1.items[0]?.included).toBe(10);
expect(childV2.items[0]?.included).toBe(20);
expect(parentV1.licenses[0]?.version).toBe(1);
expect(parentV2.licenses).toEqual([
{
license_plan_id: childId,
version: 2,
included: 2,
prepaid_only: true,
},
]);

for (const route of ["/catalog.preview_update", "/catalog.update"]) {
await expect(
autumnV2_2.post(route, {
plans: [{ plan_id: `${childId}_gap`, version: 2, name: "Gap" }],
}),
).rejects.toThrow("version must be 1, received 2");
}
},
);

test.concurrent(
`${chalk.yellowBright("licenses: same-batch historical versioning resolves from the latest version")}`,
async () => {
Expand Down
16 changes: 14 additions & 2 deletions server/tests/unit/catalog/catalog-plan-dependencies.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { expect, test } from "bun:test";
import type { CatalogPlanParams } from "@autumn/shared";
import { sortCatalogPlansByDependencies } from "@/internal/catalog/actions/catalogPlanDependencies.js";
import {
sortCatalogPlansByDependencies,
validateCatalogPlanVersionTargets,
} from "@/internal/catalog/actions/catalogPlanDependencies.js";

const plan = (
plan_id: string,
Expand All @@ -19,6 +22,15 @@ test.concurrent(

expect(
sorted.map(({ plan_id, version }) => `${plan_id}@${version ?? 0}`),
).toEqual(["child@2", "parent@0", "child@1"]);
).toEqual(["child@1", "child@2", "parent@0"]);
},
);

test.concurrent("fresh plans must start at version one", () => {
expect(() =>
validateCatalogPlanVersionTargets({
plans: [plan("fresh", 2)],
products: [],
}),
).toThrow("version must be 1, received 2");
});
Loading