blob: c4c8330e236ff61f1f0bcdaf894688830296804d [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import Fory, { ReadContext, Type, TypeIdentityKind, WriteContext } from "../packages/core/index";
import { ConfigFlags, RefFlags, TypeId } from "../packages/core/lib/type";
import { BinaryWriter } from "../packages/core/lib/writer";
import { describe, expect, test } from "@jest/globals";
const Player = {
JAVA: 0,
FLASH: 1,
} as const;
const Size = {
SMALL: 0,
LARGE: 1,
} as const;
function createSampleMediaContent() {
return {
media: {
uri: "http://javaone.com/keynote.mpg",
title: "Javaone Keynote",
width: 640,
height: 480,
format: "video/mpg4",
duration: 18000000n,
size: 58982400n,
bitrate: 262144,
has_bitrate: true,
persons: ["Bill Gates", "Steve Jobs"],
player: Player.JAVA,
copyright: "None",
},
images: [
{
uri: "http://javaone.com/keynote_large.jpg",
title: "Javaone Keynote",
width: 1024,
height: 768,
size: Size.LARGE,
},
{
uri: "http://javaone.com/keynote_small.jpg",
title: "Javaone Keynote",
width: 320,
height: 240,
size: Size.SMALL,
},
],
};
}
function buildMediaContentSchemas(mode: "unbound" | "by_id" | "by_name") {
const playerEnum =
mode === "unbound"
? Type.enum(Player)
: mode === "by_id"
? Type.enum(10, Player)
: Type.enum("media.Player", Player);
const sizeEnum =
mode === "unbound"
? Type.enum(Size)
: mode === "by_id"
? Type.enum(11, Size)
: Type.enum("media.Size", Size);
const mediaProps = {
uri: Type.string().setId(1),
title: Type.string().setId(2).setNullable(true),
width: Type.int32().setId(3),
height: Type.int32().setId(4),
format: Type.string().setId(5),
duration: Type.int64().setId(6),
size: Type.int64().setId(7),
bitrate: Type.int32().setId(8),
has_bitrate: Type.bool().setId(9),
persons: Type.list(Type.string()).setId(10),
player: playerEnum.setId(11),
copyright: Type.string().setId(12).setNullable(true),
};
const imageProps = {
uri: Type.string().setId(1),
title: Type.string().setId(2).setNullable(true),
width: Type.int32().setId(3),
height: Type.int32().setId(4),
size: sizeEnum.setId(5),
};
const media =
mode === "unbound"
? Type.struct(mediaProps)
: mode === "by_id"
? Type.struct(3, mediaProps)
: Type.struct("media.Media", mediaProps);
const image =
mode === "unbound"
? Type.struct(imageProps)
: mode === "by_id"
? Type.struct(4, imageProps)
: Type.struct("media.Image", imageProps);
const contentProps = {
media: media.clone().setId(1),
images: Type.list(image).setId(2),
};
const mediaContent =
mode === "unbound"
? Type.struct(contentProps)
: mode === "by_id"
? Type.struct(5, contentProps)
: Type.struct("media.MediaContent", contentProps);
return { playerEnum, sizeEnum, media, image, mediaContent };
}
describe("fory 2.0", () => {
test("writes Fory 2.0 root header 0x41 and rejects 1.x or reserved generations", () => {
const fory = new Fory({ compatible: true });
const bytes = fory.serialize(42);
expect(bytes[0]).toBe(ConfigFlags.xlangV2Header);
expect(bytes[0]).toBe(0x41);
expect(fory.deserialize(bytes)).toBe(42);
for (const invalidHeader of [0x00, 0x01, 0x03, 0x81, 0xc1]) {
const bad = new Uint8Array(bytes);
bad[0] = invalidHeader;
expect(() => fory.deserialize(bad)).toThrow(/protocol generation/);
}
const nativeV2 = new Uint8Array(bytes);
nativeV2[0] = 0x40;
expect(() => fory.deserialize(nativeV2)).toThrow(/support crosslanguage mode only/);
const oobV2 = new Uint8Array(bytes);
oobV2[0] = 0x43;
expect(() => fory.deserialize(oobV2)).toThrow(/outofband mode is not supported now/);
});
test("MediaContent 14-combination registered/unregistered/asymmetric matrix and wire sizes", () => {
const sample = createSampleMediaContent();
const modes = ["unbound", "by_id", "by_name"] as const;
const wireSizes: Record<string, number> = {};
for (const compatible of [true, false]) {
for (const writerMode of modes) {
for (const readerMode of modes) {
// Registered BY_ID <-> BY_NAME is an intentional registered identity mismatch.
if (
(writerMode === "by_id" && readerMode === "by_name") ||
(writerMode === "by_name" && readerMode === "by_id")
) {
continue;
}
const writerFory = new Fory({ compatible });
const readerFory = new Fory({ compatible });
const ws = buildMediaContentSchemas(writerMode);
const rs = buildMediaContentSchemas(readerMode);
expect(ws.mediaContent.identityKind).toBe(
writerMode === "unbound"
? TypeIdentityKind.UNBOUND
: writerMode === "by_id"
? TypeIdentityKind.BY_ID
: TypeIdentityKind.BY_NAME,
);
let bytes: Uint8Array;
if (writerMode === "unbound") {
// Unregistered writer works without calling register().
bytes = writerFory.serialize(sample, ws.mediaContent);
} else {
writerFory.register(ws.playerEnum);
writerFory.register(ws.sizeEnum);
writerFory.register(ws.media);
writerFory.register(ws.image);
bytes = writerFory.register(ws.mediaContent).serialize(sample);
}
if (compatible && writerMode === readerMode) {
wireSizes[writerMode] = bytes.length;
}
let decoded: unknown;
if (readerMode === "unbound") {
// Unregistered reader works without calling register().
decoded = readerFory.deserialize(bytes, rs.mediaContent);
// Second call exercises L0/L2 fast-path reuse.
expect(readerFory.deserialize(bytes, rs.mediaContent)).toEqual(sample);
} else {
readerFory.register(rs.playerEnum);
readerFory.register(rs.sizeEnum);
readerFory.register(rs.media);
readerFory.register(rs.image);
const reg = readerFory.register(rs.mediaContent);
decoded = reg.deserialize(bytes);
expect(reg.deserialize(bytes)).toEqual(sample);
}
expect(decoded).toEqual(sample);
if (writerMode === "unbound") {
// Dynamic Any must reject UNBOUND payloads.
expect(() => readerFory.deserialize(bytes)).toThrow(/UNBOUND/);
}
}
}
}
expect(wireSizes.unbound).toBeLessThan(wireSizes.by_id);
expect(wireSizes.by_id).toBeLessThan(wireSizes.by_name);
});
test("Point2D and Vector2D unregistered collision, evolution, and dynamic Any rejection", () => {
@Type.struct()
class Point2D {
@Type.float64()
x = 0;
@Type.float64()
y = 0;
}
@Type.struct()
class Vector2D {
@Type.float64()
x = 0;
@Type.float64()
y = 0;
}
const pointSchema = (Point2D.prototype as any)[Symbol.for("fory:typeInfo")]?.structTypeInfo;
void pointSchema;
const Point2DType = Type.struct({ x: Type.float64(), y: Type.float64() });
const Vector2DType = Type.struct({ x: Type.float64(), y: Type.float64() });
const RayType = Type.struct({
origin: Point2DType,
dir: Vector2DType,
});
const writerFory = new Fory({ compatible: true });
const readerFory = new Fory({ compatible: true });
const sample = { origin: { x: 1.5, y: 2.5 }, dir: { x: 3.5, y: 4.5 } };
// Same-schema collision: origin & dir share the identical 52-bit UNBOUND TypeMeta hash.
const bytes = writerFory.serialize(sample, RayType);
expect(readerFory.deserialize(bytes, RayType)).toEqual(sample);
expect(readerFory.deserialize(bytes, RayType)).toEqual(sample);
// Dynamic Any must still reject UNBOUND even after typed reads populated caches.
expect(() => readerFory.deserialize(bytes)).toThrow(/UNBOUND/);
// Decorated classes preserve distinct constructors without register().
const classWriter = new Fory({ compatible: true });
const classReader = new Fory({ compatible: true });
const p = new Point2D();
p.x = 7;
p.y = 8;
const pBytes = classWriter.serialize(p);
const decodedP = classReader.deserialize(pBytes, Point2D);
const decodedV = classReader.deserialize(pBytes, Vector2D);
expect(decodedP).toBeInstanceOf(Point2D);
expect(decodedV).toBeInstanceOf(Vector2D);
expect(decodedP).toEqual({ x: 7, y: 8 });
expect(decodedV).toEqual({ x: 7, y: 8 });
expect(() => classReader.deserialize(pBytes)).toThrow(/UNBOUND/);
// Schema evolution collision: writer sends {x, y, z}, reader reads Point2D & Vector2D {x, y}.
const Point3DType = Type.struct({
x: Type.float64(),
y: Type.float64(),
z: Type.float64(),
});
const Ray3DType = Type.struct({
origin: Point3DType,
dir: Point3DType,
});
const evolvedWriter = new Fory({ compatible: true });
const evolvedBytes = evolvedWriter.serialize(
{ origin: { x: 1, y: 2, z: 3 }, dir: { x: 4, y: 5, z: 6 } },
Ray3DType,
);
const evolvedDecoded = readerFory.deserialize(evolvedBytes, RayType);
expect(evolvedDecoded).toEqual({ origin: { x: 1, y: 2 }, dir: { x: 4, y: 5 } });
// Second read exercises L2 cached adaptation for both targets.
expect(readerFory.deserialize(evolvedBytes, RayType)).toEqual({
origin: { x: 1, y: 2 },
dir: { x: 4, y: 5 },
});
expect(() => readerFory.deserialize(evolvedBytes)).toThrow(/UNBOUND/);
});
test("supports unregistered root containers (list, set, map including nulls)", () => {
for (const compatible of [true, false]) {
const Point = Type.struct({ x: Type.int32(), y: Type.int32() });
const listType = Type.list(Point);
const setType = Type.set(Point);
const mapType = Type.map(Type.string(), Point);
const writerFory = new Fory({ compatible });
const readerFory = new Fory({ compatible });
const listData = [
{ x: 1, y: 2 },
{ x: 3, y: 4 },
];
expect(readerFory.deserialize(writerFory.serialize(listData, listType), listType)).toEqual(
listData,
);
const setData = new Set([{ x: 5, y: 6 }]);
expect(readerFory.deserialize(writerFory.serialize(setData, setType), setType)).toEqual(
setData,
);
const mapData = new Map<string | null, { x: number; y: number } | null>([
["a", { x: 10, y: 20 }],
["b", null],
[null, { x: 30, y: 40 }],
]);
expect(readerFory.deserialize(writerFory.serialize(mapData, mapType), mapType)).toEqual(
mapData,
);
}
});
test("supports unregistered enum, ext, union, and cyclic shared references", () => {
const Color = { RED: 0, GREEN: 1, BLUE: 2 } as const;
const UnboundEnum = Type.enum(Color);
const RegEnumId = Type.enum(701, Color);
const RegEnumName = Type.enum("test.Color", Color);
// Unregistered + asymmetric enum roundtrips.
for (const compatible of [true, false]) {
const w = new Fory({ compatible });
const r = new Fory({ compatible });
const regRId = r.register(RegEnumId);
const regRName = r.register(RegEnumName);
const bytes = w.serialize(Color.GREEN, UnboundEnum);
expect(r.deserialize(bytes, UnboundEnum)).toBe(Color.GREEN);
expect(regRId.deserialize(bytes)).toBe(Color.GREEN);
expect(regRName.deserialize(bytes)).toBe(Color.GREEN);
const w2 = new Fory({ compatible });
const regWName = w2.register(RegEnumName);
expect(r.deserialize(regWName.serialize(Color.BLUE), UnboundEnum)).toBe(Color.BLUE);
}
// Unregistered ext roundtrip + asymmetric ext.
for (const compatible of [true, false]) {
class CustomBox {
constructor(public code = 0) {}
}
Type.ext()(CustomBox);
const customCodec = {
write(ctx: WriteContext, value: CustomBox) {
ctx.writeVarInt32(value.code);
},
read(ctx: ReadContext, result: CustomBox) {
result.code = ctx.readVarInt32();
},
};
const w = new Fory({ compatible });
const r = new Fory({ compatible });
const wExt = w.register(CustomBox, customCodec);
const rExt = r.register(CustomBox, customCodec);
const bytes = wExt.serialize(new CustomBox(99));
const decoded = rExt.deserialize(bytes) as CustomBox;
expect(decoded).toBeInstanceOf(CustomBox);
expect(decoded.code).toBe(99);
expect(() => r.deserialize(bytes)).toThrow(/UNBOUND/);
}
// Unregistered union with unregistered struct case.
const Item = Type.struct({ name: Type.string() });
const UnboundUnion = Type.union({
0: Type.int32(),
1: Item,
});
const wUnion = new Fory({ compatible: true });
const rUnion = new Fory({ compatible: true });
const unionBytes = wUnion.serialize({ case: 1, value: { name: "hello" } }, UnboundUnion);
expect(rUnion.deserialize(unionBytes, UnboundUnion)).toEqual({
case: 1,
value: { name: "hello" },
});
expect(() => rUnion.deserialize(unionBytes)).toThrow(/UNBOUND/);
// Cyclic & shared references on unregistered struct.
const Node = Type.struct({
value: Type.int32(),
});
Node.options!.props!.next = Node.clone().setNullable(true).setTrackingRef(true);
const refFory = new Fory({ compatible: true, ref: true });
const root: any = { value: 1, next: null };
root.next = root;
const cyclicBytes = refFory.serialize(root, Node);
const cyclicOut: any = refFory.deserialize(cyclicBytes, Node);
expect(cyclicOut.value).toBe(1);
expect(cyclicOut.next).toBe(cyclicOut);
});
test("compatible skip handles removed UNBOUND structs and nested containers", () => {
const RemovedLeaf = Type.struct({ a: Type.int32(), b: Type.string() });
const RemovedNested = Type.struct({
leaf: RemovedLeaf,
items: Type.list(RemovedLeaf),
nestedItems: Type.list(Type.list(RemovedLeaf)),
byKey: Type.map(Type.string(), RemovedLeaf),
byKeyList: Type.map(Type.string(), Type.list(RemovedLeaf)),
});
const WriterSchema = Type.struct({
keep: Type.string(),
dropped: RemovedNested,
droppedNestedList: Type.list(Type.list(RemovedLeaf)),
droppedMapList: Type.map(Type.string(), Type.list(RemovedLeaf)),
after: Type.int32(),
});
const ReaderSchema = Type.struct({
keep: Type.string(),
after: Type.int32(),
});
const writerFory = new Fory({ compatible: true, ref: true });
const readerFory = new Fory({ compatible: true, ref: true });
const sharedLeaf = { a: 7, b: "shared" };
const otherLeaf = { a: 8, b: "other" };
const bytes = writerFory.serialize(
{
keep: "ok",
dropped: {
leaf: sharedLeaf,
items: [sharedLeaf, otherLeaf],
nestedItems: [[sharedLeaf], [otherLeaf]],
byKey: new Map([["k", sharedLeaf]]),
byKeyList: new Map([["g", [sharedLeaf, otherLeaf]]]),
},
droppedNestedList: [[sharedLeaf, otherLeaf]],
droppedMapList: new Map([["m", [sharedLeaf]]]),
after: 42,
},
WriterSchema,
);
expect(readerFory.deserialize(bytes, ReaderSchema)).toEqual({ keep: "ok", after: 42 });
// Second read exercises cached skip path, while dynamic Any still rejects UNBOUND.
expect(readerFory.deserialize(bytes, ReaderSchema)).toEqual({ keep: "ok", after: 42 });
expect(() => readerFory.deserialize(bytes)).toThrow(/UNBOUND/);
});
test("RefReader rejects out-of-bounds refId", () => {
const fory = new Fory({ compatible: false, ref: true });
const writer = new BinaryWriter({});
writer.writeUint8(ConfigFlags.xlangV2Header);
writer.writeInt8(RefFlags.RefFlag);
writer.writeVarUInt32(99);
expect(() => fory.deserialize(writer.dump())).toThrow(/Invalid reference id/);
});
test("Registration Freeze blocks register() after first serialize or deserialize (even on failure)", () => {
const A = Type.struct(9001, { x: Type.int32() });
const B = Type.struct(9002, { y: Type.int32() });
// Frozen after successful serialize.
const f1 = new Fory();
const serA = f1.register(A);
serA.serialize({ x: 1 });
expect(() => f1.register(B)).toThrow(/Cannot register types after/);
// Frozen after failed deserialize.
const f2 = new Fory();
f2.register(A);
expect(() => f2.deserialize(new Uint8Array([0x01]))).toThrow();
expect(() => f2.register(B)).toThrow(/Cannot register types after/);
// Unregistered BY_ID type passed to serialize/deserialize must also fail after freeze.
expect(() => f2.serialize({ y: 2 }, B)).toThrow(/must be registered before first use/);
});
test("rejects conflicting registered identities for enum, ext, union, and non-evolving struct", () => {
for (const compatible of [true, false]) {
const fory = new Fory({ compatible });
const EnumA = { RED: "red", GREEN: "green" } as const;
const EnumB = { BLUE: "blue", YELLOW: "yellow" } as const;
const enumASchema = Type.enum(41, EnumA);
const enumBSchema = Type.enum(42, EnumB);
const enumUnboundSchema = Type.enum(EnumB);
const namedEnumASchema = Type.enum("test.EnumA", EnumA);
const namedEnumBSchema = Type.enum("test.EnumB", EnumB);
class ExtA {
n = 0;
}
class ExtB {
n = 0;
}
Type.ext(51)(ExtA);
Type.ext(52)(ExtB);
const extImpl = {
write(ctx: WriteContext, v: { n: number }) {
ctx.writeInt32(v.n);
},
read(ctx: ReadContext, result: { n: number }) {
result.n = ctx.readInt32();
},
};
const unionASchema = Type.union(61, { 0: Type.int32(), 1: Type.string() });
const unionBSchema = Type.union(62, { 0: Type.int32(), 1: Type.string() });
const structASchema = Type.struct(71, { x: Type.int32() });
const structBSchema = Type.struct(72, { x: Type.int32() });
const regEnumA = fory.register(enumASchema);
const regEnumB = fory.register(enumBSchema);
const regUnboundEnum = fory.register(enumUnboundSchema);
const regNamedEnumA = fory.register(namedEnumASchema);
const regNamedEnumB = fory.register(namedEnumBSchema);
const regExtA = fory.register(ExtA, extImpl);
const regExtB = fory.register(ExtB, extImpl);
const regUnionA = fory.register(unionASchema);
const regUnionB = fory.register(unionBSchema);
const regStructA = fory.register(structASchema);
const regStructB = fory.register(structBSchema);
// Matching IDs succeed.
const enumABytes = regEnumA.serialize(EnumA.RED);
expect(fory.deserialize(enumABytes, enumASchema)).toBe(EnumA.RED);
expect(regEnumA.deserialize(enumABytes)).toBe(EnumA.RED);
// Conflicting known numeric enum ID must fail on both registered and unbound targets.
expect(() => fory.deserialize(enumABytes, enumBSchema)).toThrow(/identity mismatch/i);
expect(() => regEnumB.deserialize(enumABytes)).toThrow(/identity mismatch/i);
expect(() => regUnboundEnum.deserialize(enumABytes)).toThrow(/identity mismatch/i);
// Matching named enums succeed; conflicting named enums fail.
const namedEnumABytes = regNamedEnumA.serialize(EnumA.RED);
expect(regNamedEnumA.deserialize(namedEnumABytes)).toBe(EnumA.RED);
expect(() => regNamedEnumB.deserialize(namedEnumABytes)).toThrow(/mismatch/i);
expect(() => regUnboundEnum.deserialize(namedEnumABytes)).toThrow(/identity mismatch/i);
// Asymmetric unknown wire enum ID still adapts to an unbound enum target.
const separateWriter = new Fory({ compatible });
const unknownEnumBytes = separateWriter.register(Type.enum(999, EnumA)).serialize(EnumA.RED);
expect(regUnboundEnum.deserialize(unknownEnumBytes)).toBe(EnumB.BLUE);
// EXT conflicts fail; matching succeeds.
const extABytes = regExtA.serialize({ n: 123 });
expect((regExtA.deserialize(extABytes) as ExtA).n).toBe(123);
expect(() => regExtB.deserialize(extABytes)).toThrow(/identity mismatch/i);
expect(() => fory.deserialize(extABytes, ExtB)).toThrow(/identity mismatch/i);
// Union conflicts fail; matching succeeds.
const unionABytes = regUnionA.serialize({ case: 0, value: 7 });
expect(regUnionA.deserialize(unionABytes)).toEqual({ case: 0, value: 7 });
expect(() => regUnionB.deserialize(unionABytes)).toThrow(/identity mismatch/i);
expect(() => fory.deserialize(unionABytes, unionBSchema)).toThrow(/identity mismatch/i);
// Struct conflicts fail; matching succeeds.
const structABytes = regStructA.serialize({ x: 9 });
expect(regStructA.deserialize(structABytes)).toEqual({ x: 9 });
expect(() => regStructB.deserialize(structABytes)).toThrow(/mismatch/i);
expect(() => fory.deserialize(structABytes, structBSchema)).toThrow(/mismatch/i);
}
});
});