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(javascript): Added serialization and serialization for Type Meta Layer #1825

Merged
merged 35 commits into from
Sep 28, 2024
Merged
Show file tree
Hide file tree
Changes from 31 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
d9ee8cd
Added wrapper on typemeta
Forchapeatl Sep 2, 2024
b0d73b9
Add files via upload
Forchapeatl Sep 2, 2024
03f6227
Update object.ts
Forchapeatl Sep 2, 2024
f639b3c
using BinaryBuilderReader
Forchapeatl Sep 7, 2024
5d30608
Removed MetaString and Using TypeMeta
Forchapeatl Sep 7, 2024
b88b616
Update builder.ts
Forchapeatl Sep 7, 2024
3a4e9f4
reoved TypeMeta
Forchapeatl Sep 9, 2024
a7d7bf1
added ownName to binary.reader
Forchapeatl Sep 9, 2024
b81255a
moved from TypeMetaWrapper to TypeMetaBuilder
Forchapeatl Sep 9, 2024
d259a2d
Added TypeMeta
Forchapeatl Sep 9, 2024
2780033
Added TypeMeta to constructor
Forchapeatl Sep 11, 2024
81b274f
removed TypeMeta from constructor
Forchapeatl Sep 12, 2024
b67f509
FIxed syntax error
Forchapeatl Sep 14, 2024
753869e
fixed lint errors
Forchapeatl Sep 24, 2024
ef92c34
Fixed Meta Layer Buffer
Forchapeatl Sep 24, 2024
615a473
fixed byte length over flow
Forchapeatl Sep 24, 2024
42845e6
removed BinaryReader Builder dependency
Forchapeatl Sep 24, 2024
1434328
fixed lint errors
Forchapeatl Sep 24, 2024
418f4a5
Fixed Meta Layer Buffer
Forchapeatl Sep 24, 2024
7b666c2
fixed lint errors
Forchapeatl Sep 24, 2024
4a3b3f5
fixed lint errors
Forchapeatl Sep 24, 2024
aedf2aa
fixed lint errors
Forchapeatl Sep 24, 2024
f3b87da
Merge branch 'main' into Forchapeatl-TypeMeta
Forchapeatl Sep 24, 2024
9c48706
switched to camel casing
Forchapeatl Sep 26, 2024
b9c3cc9
switched to camel casing
Forchapeatl Sep 26, 2024
636fb05
switched to camel casing
Forchapeatl Sep 26, 2024
5418532
Added Compatible mode
Forchapeatl Sep 27, 2024
7cd91cd
Added mode to fury config
Forchapeatl Sep 27, 2024
2bb55ad
exported Mode
Forchapeatl Sep 27, 2024
1555617
used Mode from type.ts
Forchapeatl Sep 27, 2024
f107fc1
SchemaConsistent for default mode
Forchapeatl Sep 27, 2024
37e88d8
Reading TypeMeta only in Compatible mode
Forchapeatl Sep 28, 2024
91fc901
Imported Fury Mode
Forchapeatl Sep 28, 2024
1941170
fixed lint errors
Forchapeatl Sep 28, 2024
83bb434
Merge branch 'main' into Forchapeatl-TypeMeta
theweipeng Sep 28, 2024
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
5 changes: 4 additions & 1 deletion javascript/packages/fury/lib/fury.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,26 @@ import ClassResolver from "./classResolver";
import { BinaryWriter } from "./writer";
import { BinaryReader } from "./reader";
import { ReferenceResolver } from "./referenceResolver";
import { ConfigFlags, Serializer, Config, Language, MAGIC_NUMBER } from "./type";
import { ConfigFlags, Serializer, Config, Language, MAGIC_NUMBER, Mode } from "./type";
import { OwnershipError } from "./error";
import { InputType, ResultType, TypeDescription } from "./description";
import { generateSerializer, AnySerializer } from "./gen";
import { TypeMeta } from "./meta/TypeMeta";

export default class {
binaryReader: BinaryReader;
binaryWriter: BinaryWriter;
classResolver = new ClassResolver();
referenceResolver: ReferenceResolver;
anySerializer: AnySerializer;
typeMeta = TypeMeta;

constructor(public config: Config = {
refTracking: false,
useSliceString: false,
hooks: {
},
mode: Mode.SchemaConsistent,
}) {
this.binaryReader = new BinaryReader(config);
this.binaryWriter = new BinaryWriter(config);
Expand Down
14 changes: 13 additions & 1 deletion javascript/packages/fury/lib/gen/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,17 @@ import { getMeta } from "../meta";
import { TypeDescription } from "../description";
import Fury from "../fury";

class BinaryReaderBuilder {
class TypeMetaBuilder {
constructor(private fury: string) {

}

fromBytes(reader: string) {
return `${this.fury}.typeMeta.fromBytes(${reader})`;
}
}

export class BinaryReaderBuilder {
constructor(private holder: string) {

}
Expand Down Expand Up @@ -309,6 +319,7 @@ class ClassResolverBuilder {
export class CodecBuilder {
reader: BinaryReaderBuilder;
writer: BinaryWriterBuilder;
typeMeta: TypeMetaBuilder; // Use the TypeMetaWrapper
referenceResolver: ReferenceResolverBuilder;
classResolver: ClassResolverBuilder;

Expand All @@ -321,6 +332,7 @@ export class CodecBuilder {
this.writer = new BinaryWriterBuilder(bw);
this.classResolver = new ClassResolverBuilder(cr);
this.referenceResolver = new ReferenceResolverBuilder(rr);
this.typeMeta = new TypeMetaBuilder("fury"); // Initialize the TypeMetaWrapper
}

furyName() {
Expand Down
31 changes: 13 additions & 18 deletions javascript/packages/fury/lib/gen/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,7 @@ import { fromString } from "../platformBuffer";
import { CodegenRegistry } from "./router";
import { BaseSerializerGenerator, RefState } from "./serializer";
import SerializerResolver from "../classResolver";
import { MetaString } from "../meta/MetaString";

// Ensure MetaString methods are correctly implemented
const computeMetaInformation = (description: any) => {
const metaInfo = JSON.stringify(description);
return MetaString.encode(metaInfo);
};

const decodeMetaInformation = (encodedMetaInfo: Uint8Array) => {
return MetaString.decode(encodedMetaInfo);
};
import { FieldInfo, TypeMeta } from "../meta/TypeMeta";

function computeFieldHash(hash: number, id: number): number {
let newHash = (hash) * 31 + (id);
Expand Down Expand Up @@ -80,11 +70,18 @@ class ObjectSerializerGenerator extends BaseSerializerGenerator {
writeStmt(accessor: string): string {
const options = this.description.options;
const expectHash = computeStructHash(this.description);
const metaInformation = Buffer.from(computeMetaInformation(this.description));
// const metaInformation = Buffer.from(computeMetaInformation(this.description));
const fields = Object.entries(this.description).map(([key, value]) => {
return new FieldInfo(key, value.type);
});
const typeMetaBinary = new Uint8Array(TypeMeta.fromFields(256, fields).toBytes());
const typeMetaDeclare = this.scope.declare("typeMeta", `new Uint8Array([${typeMetaBinary.toString()}])`);

return `
${this.builder.writer.int32(expectHash)};
${this.builder.writer.buffer(`Buffer.from("${metaInformation.toString("base64")}", "base64")`)};

${this.builder.writer.buffer(typeMetaDeclare)};
theweipeng marked this conversation as resolved.
Show resolved Hide resolved

${Object.entries(options.props).sort().map(([key, inner]) => {
const InnerGeneratorClass = CodegenRegistry.get(inner.type);
if (!InnerGeneratorClass) {
Expand All @@ -99,9 +96,8 @@ class ObjectSerializerGenerator extends BaseSerializerGenerator {
readStmt(accessor: (expr: string) => string, refState: RefState): string {
const options = this.description.options;
const expectHash = computeStructHash(this.description);
const encodedMetaInformation = computeMetaInformation(this.description);
const result = this.scope.uniqueName("result");
const pass = this.builder.reader.int32();

return `
if (${this.builder.reader.int32()} !== ${expectHash}) {
throw new Error("got ${this.builder.reader.int32()} validate hash failed: ${this.safeTag()}. expect ${expectHash}");
Expand All @@ -111,8 +107,9 @@ class ObjectSerializerGenerator extends BaseSerializerGenerator {
return `${CodecBuilder.safePropName(key)}: null`;
}).join(",\n")}
};

${this.maybeReference(result, refState)}
${this.builder.reader.buffer(encodedMetaInformation.byteLength)}
${this.builder.typeMeta.fromBytes(this.builder.reader.ownName())}
theweipeng marked this conversation as resolved.
Show resolved Hide resolved
${Object.entries(options.props).sort().map(([key, inner]) => {
const InnerGeneratorClass = CodegenRegistry.get(inner.type);
if (!InnerGeneratorClass) {
Expand All @@ -125,8 +122,6 @@ class ObjectSerializerGenerator extends BaseSerializerGenerator {
`;
}

// /8 /7 /20 % 2
// is there a ratio from length / deserializer
private safeTag() {
return CodecBuilder.replaceBackslashAndQuote(this.description.options.tag);
}
Expand Down
8 changes: 2 additions & 6 deletions javascript/packages/fury/lib/meta/MetaString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,21 +59,17 @@ export class MetaString {

// Decoding function that extracts bits per character from the first byte
static decode(bytes: Uint8Array): string {
const bitsPerChar = bytes[0] & 0x0F;
const bitsPerChar = bytes[0];
const totalBits = (bytes.length * 8); // Adjusted for metadata bits
const chars: string[] = [];
let currentBit = 8; // Start after the first 8 metadata bits

while (currentBit < totalBits) {
while (currentBit + bitsPerChar <= totalBits) {
let value = 0;
for (let i = 0; i < bitsPerChar; i++) {
const bytePos = Math.floor(currentBit / 8);
const bitPos = currentBit % 8;

if (bytePos >= bytes.length) {
throw new RangeError("Offset is outside the bounds of the DataView");
}

if (bytes[bytePos] & (1 << (7 - bitPos))) {
value |= (1 << (bitsPerChar - i - 1));
}
Expand Down
144 changes: 144 additions & 0 deletions javascript/packages/fury/lib/meta/TypeMeta.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*
* 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 { BinaryWriter } from "../writer";
import { BinaryReader } from "../reader";
import { MetaString } from "./MetaString";

enum Encoding {
Utf8,
AllToLowerSpecial,
LowerUpperDigitSpecial,
}

export class FieldInfo {
constructor(private fieldName: string, private fieldId: number) {
}

static u8ToEncoding(value: number) {
switch (value) {
case 0x00:
return Encoding.Utf8;
case 0x01:
return Encoding.AllToLowerSpecial;
case 0x02:
return Encoding.LowerUpperDigitSpecial;
}
}

static fromBytes(reader: BinaryReader) {
const header = reader.uint8();
let size = (header & 0b11100000) >> 5;
size = (size === 0b111) ? reader.varInt32() + 7 : size;
const typeId = reader.int16();
// reader.skip(size);
const fieldName = MetaString.decode(reader.buffer(size)); // now we commentd this line , the code work well
return new FieldInfo(fieldName, typeId);
}

toBytes() {
const writer = new BinaryWriter({});
const metaString = MetaString.encode(this.fieldName);
let header = 1 << 2;
const size = metaString.byteLength;
const bigSize = size >= 7;
if (bigSize) {
header |= 0b11100000;
writer.uint8(header);
writer.varInt32(size - 7);
} else {
header |= size << 5;
writer.uint8(header);
}
writer.int16(this.fieldId);
writer.buffer(metaString);
return writer.dump();
}
}

// Using classes to emulate struct methods in Rust
class TypeMetaLayer {
constructor(private typeId: number, private fieldInfo: FieldInfo[]) {
}

getTypeId() {
return this.typeId;
}

getFieldInfo() {
return this.fieldInfo;
}

toBytes() {
const writer = new BinaryWriter({});
writer.varInt32(this.fieldInfo.length);
writer.varInt32(this.typeId);
for (const field of this.fieldInfo) {
writer.buffer(field.toBytes());
}
return writer.dump();
}

static fromBytes(reader: BinaryReader) {
const fieldNum = reader.varInt32();
const typeId = reader.varInt32();
const fieldInfo = [];
for (let i = 0; i < fieldNum; i++) {
fieldInfo.push(FieldInfo.fromBytes(reader));
}
return new TypeMetaLayer(typeId, fieldInfo);
}
}

export class TypeMeta {
constructor(private hash: bigint, private layers: TypeMetaLayer[]) {
}

getFieldInfo() {
return this.layers[0].getFieldInfo();
}

getTypeId() {
return this.layers[0].getTypeId();
}

static fromFields(typeId: number, fieldInfo: FieldInfo[]) {
return new TypeMeta(BigInt(0), [new TypeMetaLayer(typeId, fieldInfo)]);
}

static fromBytes(reader: BinaryReader) {
const header = reader.uint64();
const hash = header >> BigInt(8);
const layerCount = header & BigInt(0b1111);
const layers = [];
for (let i = 0; i < layerCount; i++) {
layers.push(TypeMetaLayer.fromBytes(reader));
}
return new TypeMeta(hash, layers);
}

toBytes() {
const writer = new BinaryWriter({});
writer.uint64(BigInt((this.hash << BigInt(8)) | BigInt((this.layers.length & 0b1111))));
for (const layer of this.layers) {
writer.buffer(layer.toBytes());
}
return writer.dump();
}
}
6 changes: 6 additions & 0 deletions javascript/packages/fury/lib/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,19 @@ export interface Hps {
stringCopy: (str: string, dist: Uint8Array, offset: number) => void;
}

export enum Mode {
SchemaConsistent,
Compatible,
}

export interface Config {
hps?: Hps;
refTracking?: boolean;
useSliceString?: boolean;
hooks?: {
afterCodeGenerated?: (code: string) => string;
};
mode?: Mode;
}

export enum Language {
Expand Down
Loading