GithubHelp home page GithubHelp logo

creditkarma / thrift-typescript Goto Github PK

View Code? Open in Web Editor NEW
148.0 148.0 35.0 2.86 MB

Generate TypeScript from Thrift IDL files

License: Apache License 2.0

Thrift 0.43% TypeScript 99.55% JavaScript 0.02%
microservices nodejs rpc thrift typescript

thrift-typescript's People

Contributors

csordasmarton avatar hayes avatar ian-harshman-ck avatar kevin-greene-ck avatar kevinbgreene avatar ksonnad avatar nnance avatar phated avatar ramakrishna-battala-ck avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

thrift-typescript's Issues

Type check assignment of default field values

The parser does not guarantee that default values are assigned properly. For example you could give a map<i32,string> the default value of 'foobar'. We should validate these assignments and give the client a useful error.

Remove `success` property on Struct generics

I noticed in the proof-of-concept that a success boolean property was being added to structs but it doesn't seem like the thrift binary does that. What is that property used for?

Always return a promise from service methods

TypeScript supports Promises but doesn't shim them; however, it does shim async/await. This would require a shim library to be loaded (I believe the thrift library already requires & exports the Q promise library).

Enums in TypeScript are very lax

In researching enum in TypeScript, I found that it is a subtype of number, which makes it very lax during type checking.

For example, the following is valid TypeScript:

enum Operation {
  ADD, SUBTRACT
}

const op: Operation = 4; // Invalid enum value

Should we use the enum type to generate thrift enum definition or should we do something else?

Rename interfaces with `I` prefix

I'm doing some more research into Interface creation for Structs (and other data types) to implement. These interfaces can also be used in the constructor as the typings for args, which fixes a problem I was having with nested container types.

I'm currently thinking the names should just be the Struct name with "Interface" appended. e.g. class MyStruct implements MyStructInterface @nnance thoughts?

Utilize a sub-namespace of js.ts

We could either use the standard js namespace or maybe a ts namespace? I guess we could use a js.ts or js.typescript if we wanted to be verbose.

Investigate typings for thirft-parser IDL

Someone submitted typings to the thrift-parser project but I'm not sure how thorough they are. I need to investigate and use them where appropriate (or fix if they are missing things).

Target node/ES2015 only

A lot of my open questions seem to be around features that would make things much simpler (Promises, Maps, etc). What environments are we targeting?

How should we test the Node abstraction?

Should we test the result of toAST() is a specific AST shape or should we pass the result into a printer and compare the output text string?

I'm open to other options also.

Add support for a Thrfit Struct interface

I some use cases we need to have a generic Thrift Struct Interface defined in typings and added to the code generator so we can identify something as a Thrift Struct.

Need to resolve `include` paths

Once this syntax is implemented in thrift-parser, this module will need to resolve them.

A few decisions to make:

  • Should it read the includes by default or only when an option is set (-r flag in the traditional thrift parser)?
  • Should separate output files be generated or combined into one? Ref #14
  • Should thrift-typescript or thrift-parser be responsible for resolving the location of the file? Currently, I'm resolving in thrift-parser but that might be wrong. This one has been answered by upstream; it seems that thrift-typescript will be doing the resolution.

Typesafe Struct Constructors

This is something that stems from the original Apache implementation, but I think it could be improved upon.

In the generated code, thrift structs are currently populated via the read instance method:

const struct = new MyStruct()
struct.read(inputProtocol)

This means that the MyStruct's constructor arg has to be optional, otherwise we wouldn't be able to call the empty constructor. Unfortunately this makes constructors less type-safe for consumers. Even if MyStruct has a bunch of required fields...

struct MyStruct {
  1: required i32 field1
  2: required string field2
   ...

... the constructor can still be called with no arguments because the generated code requires it.

const struct = new MyStruct() // compiles, but should require fields

Alternative Approach

The read methods can be static. Something like

const struct = MyStruct.read(input)

This would free up the constructor signature to require a valid set of input arguments, which would result in required fields being type-checked (If a struct has no fields, we could make an exception in that case).

class MyStruct {
    constructor(args: IMyStructArgs) {...}  // constructor args are no longer optional
}

I've POC'd this by manually editing generated code and it seems to work just fine, though I haven't looked at memory / time complexity.

Anyway, not a high priority, just some food for thought.

Prefer handlebars templates over AST?

When thinking about this effort, I had envisioned transforming the Thrift AST generated by thrift-parser to a JS AST and then use a tool to output the generated JS. I see that a lot of work has been done with handlerbars templates and I'm not sure it's worth it to move away from that. @nnance any thoughts?

Should aliases that are resolved to a base type be eliminated from output?

The way we are currently resolving:

struct Embed {};

typedef Embed myEmbed;

struct MyStruct {
    1: myEmbed embedded
}

is to:

export type myEmbed = Embed;

export class Embed {};

export class MyStruct {
    ...
    embedded?: Embed; // myEmbed was resolved to Embed
    ...
}

This is resolving the alias to an alias down to the simplest reference. Do we want to keep the myEmbed type alias in the generated output when this happens?

demo has something wrong

service Caluculator {
i32 add(1: i32 left, 2: i32 right)
i32 subtract(1: i32 left, 2: i32 right)
}

import { Calculator } from './codegen/calculator'
two word type error

Should service generation be done before new Thrift client library?

@nnance While trying to understand the way node's thrift client library does send/receive for services, I found that it does some really hacky stuff (they even have a TODO to fix it) that would likely be going away. Is it worth the effort to do code generation that interops with their current implementation?

Enum aliases can't be used

It seems that it's possible to alias an enum in typescript but it can't be referenced from outside the module.

e.g.

export namespace MyThing {
    export type enumAlias = MyEnum;
    export type anotherAlias = MyEnum;
    export enum MyEnum {
        ADD,
        SUBTRACT,
        MULTIPLY,
        DIVIDE
    }
}

MyThing.enumAlias.ADD; // [ts] Property 'enumAlias' does not exist on type 'typeof MyThing'.

What should we do? Ref #30

Add version info to generated source

We should add a docblock header to the top of each source file so we can trace generated source back to a particular version of this tool.

Something like:

/**
 * Generated by @creditkarma/thrift-typescript
 * Version 0.0.2
 */

Add a debugger similar to thrift-parser

For the static analysis phases (resolver, validator) we should report errors similar to how it is being done in the parser. Don't throw on first error, collect errors and print errors with the line of source that caused the error, highlighting the problem token.

Allow * for language choice in namespace declarations

namespace * MyNamespace

is recommended in https://www.manning.com/books/programmers-guide-to-apache-thrift-cx (please ignore the cancelled message) and compiles fine using the namespace in all languages (that I've tried) using the Apache Thrift code generator.

With thrift-typescript I encounter:

    Parse Failure: 2 errors found:


    Scan Error:

    Message: Unexpected token: *

    4 | namespace * MyNamespace
                  ^


    Parse Error:

    Message: Unable to find name identifier for namespace

    4 | namespace * MyNamespace

I can bypass it by replacing * with js but then I am going to have to duplicate the namespace line for each language I want to support.

Is this an approach that thrift-typescript could support or is my current approach actually a bad idea in practice?

Generate a single file with exported namespaces

The thrift binary outputs a bunch of different files (one *_types.js per thrift file and one file per service). Should we generate a single file instead? It seems like it would be easier from an import/usage perspective.

Do we want to push some assumptions in the output?

I am wondering if we should generate the output with assumptions about how the CK team uses the client library.

The best example I found so far is:

// The Thrift tutorial teaches Struct usage like:
var work = new Work();
work.op = tutorial.Operation.DIVIDE;
work.num1 = 1;
work.num2 = 0;

// But the Constructor can (and must for required) take the properties upon construction
var work = new Work({
  op: tutorial.Operation.DIVIDE,
  num1: 1,
  num2: 0
});

Since we are leveraging TypeScript, we can leverage Interfaces as our constructor argument and avoid a lot of if statements in the constructor assignment. However, maybe this pushes the wrong assumptions or we don't want to push them. @nnance thoughts?

there are some wrong when create dir in windows

function mkdir(dirPath) {
console.log("dirPath:" + dirPath + " " + path.sep);

var parts = dirPath.split(path.sep).filter((val) => val !== '');

// i add this code it can run in windows
if (os.platform() === 'win32') {
parts = parts.slice(1)
}
if (parts.length > 0 && path.isAbsolute(dirPath)) {
createPath(parts, rootDir());
}
else if (parts.length > 0) {
createPath(parts, process.cwd());
}
}

Services cannot return promises

I'll use this simple service for reference.

service MyService {
   Response call(1: Request request)
}

In this case, the tool generates something like

export interface IMyServiceHandler<Context> {
    call: (request: Request, context: Context) => Response;
}

Notice that the return type does not allow for promises to be returned. I believe we can make the return type Response | Promise<Response> as a non-breaking change.

Allocation failed - JavaScript heap out of memory

For thrift files whose dependency tree (the file and all of the includes) can be large node can sometimes run out of memory while running the generator.

The solution for this is to build a file, save it and deallocate as much data as possible before moving on to the next file. Currently we are keeping all of the file's data after the file has been rendered, keeping all data until the entire dependency tree has been rendered.

A temporary solution for this is to increase the memory allocated for node when running the generator:

$ node --max_old_space_size=8192 dist/main/bin/index.js <options>

Separate normalization/validation pass

I'm thinking their should be some sort of normalization and validation done before the code generation. The reason I think this is beneficial is to resolve custom types and find out if anything used wasn't declared in the definition.

If this makes sense to have, should both be done in a single pass or should it be split into 2 separate phases?

Incorrect switch case fall-through with "--target thrift-server"

In the genrated Processor code, the process() function looks like the following:

public process(input: thrift.TProtocol, output: thrift.TProtocol, context: Context): Promise<Buffer> {
            return new Promise<Buffer>((resolve, reject): void => {
                const metadata: thrift.IThriftMessage = input.readMessageBegin();
                const fieldName: string = metadata.fieldName;
                const requestId: number = metadata.requestId;
                const methodName: string = "process_" + fieldName;
                switch (methodName) {
                    case "process_foo": {
                        resolve(this.process_foo(requestId, input, output, context));
                    }
                    case "process_bar": {
                        resolve(this.process_bar(requestId, input, output, context));
                    }
                    default: {
                        input.skip(thrift.TType.STRUCT);
                        input.readMessageEnd();
                        const errMessage = "Unknown function " + fieldName;
                        const err = new thrift.TApplicationException(thrift.TApplicationExceptionType.UNKNOWN_METHOD, errMessage);
                        output.writeMessageBegin(fieldName, thrift.MessageType.EXCEPTION, requestId);
                        thrift.TApplicationExceptionCodec.encode(err, output);
                        output.writeMessageEnd();
                        resolve(output.flush());
                    }
                }
            });

You can notice there is no "break;" sentence in the case clauses.
This causes all the handler functions to actually be called, as long as they have no arguments (if they do, argument parsing fails, and the function is not called).

The result is that having functions without arguments in a service is nearly unusable.

Needs to have @types/thrift installed

While implementing Exceptions, I found that TypeScript doesn't like extending with JS constructors (such as Thrift.TException) but by installing @types/thrift, that constructor is declared as a proper class and TypeScript stops complaining.

How should we handle needing this dependency installed?

types.hbs doesn't support containers

Currently breaking due to being unable to call .toUpperCase on the type because it is an object but they have much different logic so it needs to get implemented.

Use Map data type to store Map container data

I found a bug with the output in the JS that the thrift binary outputs.

Sample:

map<bool, string> = {false: 'test'}

When this is serialized, it will become {true: 'test'} on the server because false is resolved as a string and checked for truthiness.

Default negative numbers can't be parsed

if i have something like this:

struct SomeStruct {
  1: optional i16 bpm = 0
  2: optional byte confidence = -1
}

The parser complains:

Parse Failure: 1 errors found:


Parse Error:

Message: FieldType expected but found: IntegerLiteral

174 |   2: optional byte confidence = -1
                                      ^

/usr/local/lib/node_modules/@creditkarma/thrift-typescript/dist/main/utils.js:25
            throw new Error('Unable to parse source');

Only support npm version of thrift library

While reviewing container types, I've found some inconsistencies between the thrift.js clientside library and the thrift library on npm. Would it be better to output code that utilizes the npm version of the library?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.