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(compiler): support json to struct conversion #3648

Merged
merged 12 commits into from
Aug 12, 2023

Conversation

hasanaburayyan
Copy link
Contributor

@hasanaburayyan hasanaburayyan commented Jul 30, 2023

The changes in this PR make it possible to call fromJson on any compatible struct definition.

Implementation notes:

Previously we treated the jsification of structs as a no-op since there is not a JS equivalent. So with this change structs now JSify into a Struct file that contains a class with a static jsonSchema and a fromJson function which will allow for field validation at runtime.

The schema generated adheres to: https://json-schema.org/understanding-json-schema/

take this simple example Wing code:

struct MyStruct {
	myField: str;
	myOtherField: num;
}

this will now generate a JS file named MyStruct.Struct.js which looks like this:

module.exports = function(stdStruct, fromInline) {
  class MyStruct {
    static jsonSchema() {
      return {
        id: "/MyStruct",
        type: "object",
        properties: {
          myField: { type: "string" },
          myOtherField: { type: "number" },
        },
        required: [
          "myField",
          "myOtherField",
        ],
        $defs: {
        }
      }
    }
    static fromJson(obj) {
      return stdStruct._validate(obj, this.jsonSchema())
    }
    static _toInflightType(context) {
      return fromInline(`require("./MyStruct.Struct.js")(${ context._lift(stdStruct) })`);
    }
  }
  return MyStruct;
};

The piece that brings this all together is the addition of the Struct class in our std that only has a fromJson() methods at the moment that is a Wing macro. The macro just calls the fromJson() method in the generated javascript.

Misc

We want to stop the user at compile time from calling fromJson on a struct that cannot be represented by a Json value ie

struct MyStruct {
	b: cloud.Bucket;
}
let j = {};
MyStruct.fromJson(j);

to prevent this I added a check in the typechecker for structs to confirm that if fromJson is called that all the fields in the struct are valid for conversion attempt

See image below for error when attempting:
image

Closes: #3653
Closes: #3139

TODO:

  • separate the work done here and the remaining work into different tickets.
  • update language reference

Followup issues that are out of scope for this PR:

Checklist

  • Title matches Winglang's style guide
  • Description explains motivation and solution
  • Tests added (always)
  • Docs updated (only required for features)
  • Added pr/e2e-full label if this feature requires end-to-end testing

By submitting this pull request, I confirm that my contribution is made under the terms of the Wing Cloud Contribution License.

@hasanaburayyan hasanaburayyan requested a review from a team as a code owner July 30, 2023 17:39
Copy link
Contributor

@yoav-steinberg yoav-steinberg left a comment

Choose a reason for hiding this comment

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

Very nice work
added some questions.

examples/tests/error/struct_from_json_2.w Outdated Show resolved Hide resolved
libs/wingc/src/type_check.rs Outdated Show resolved Hide resolved
examples/tests/valid/struct_json_conversion.w Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/type_check.rs Show resolved Hide resolved
libs/wingsdk/src/std/struct.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@eladb eladb left a comment

Choose a reason for hiding this comment

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

Great job 👏

libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
@eladb
Copy link
Contributor

eladb commented Jul 31, 2023

I was wondering if it might make more sense to generate a json schema and use a standard schema validation utility.

We also want to support something like:

let s = MyStruct.jsonSchema();

s.validate()
s.toJson()
// etc..

The use case is for example using wing structs as api shapes with OpenAPI specs.

@yoav-steinberg
Copy link
Contributor

yoav-steinberg commented Jul 31, 2023

I was wondering if it might make more sense to generate a json schema and use a standard schema validation utility.

After reviewing I thought of this too. I think we should have a getSchema method in std.Struct, the validate method should be:

var v = new require('jsonschema').Validator(); // see https://www.npmjs.com/package/jsonschema
v.validate(obj, self.getSchema());

If there's no major issue with this approach I suggest doing another dev push to making it work this way and void our custom validation code.

@hasanaburayyan
Copy link
Contributor Author

hasanaburayyan commented Jul 31, 2023

I was wondering if it might make more sense to generate a json schema and use a standard schema validation utility.

@yoav-steinberg @eladb When I originally started I wanted to generate schemas and went down a few learning rabbit holes, and did not think it was something we could easily do (because of nested arrays that can contain user defined structs), thats when I shifted gears to this approach.

However, back then I was younger, naive and since then I have grown and learned more about the way bundling and some of the other JavaScript vodoo works 😂 😂 and I think generating these schemas for use in a standard validator can be "easishly" done.

Im going to convert this PR to a WIP and investigate changing to that pattern (assuming there are not any objections)

@hasanaburayyan hasanaburayyan marked this pull request as draft July 31, 2023 13:07
@hasanaburayyan hasanaburayyan marked this pull request as ready for review August 1, 2023 16:30
@hasanaburayyan hasanaburayyan force-pushed the hasan/struct-conversion-almost-there branch from 1c1f230 to 4e057c3 Compare August 1, 2023 16:38
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
libs/wingc/src/jsify.rs Show resolved Hide resolved
libs/wingc/src/jsify.rs Show resolved Hide resolved
libs/wingc/src/jsify.rs Show resolved Hide resolved
libs/wingc/src/jsify.rs Outdated Show resolved Hide resolved
@hasanaburayyan hasanaburayyan force-pushed the hasan/struct-conversion-almost-there branch from 4e057c3 to a95c606 Compare August 2, 2023 14:11
@monadabot monadabot added the ⚠️ pr/review-mutation PR has been mutated and will not auto-merge. Clear this label if the changes look good! label Aug 2, 2023
Copy link
Contributor

@yoav-steinberg yoav-steinberg left a comment

Choose a reason for hiding this comment

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

Very nice work using schemas

@hasanaburayyan hasanaburayyan force-pushed the hasan/struct-conversion-almost-there branch from 0af2e0e to 31c0990 Compare August 2, 2023 22:25
Copy link
Contributor

@eladb eladb left a comment

Choose a reason for hiding this comment

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

Some issue with module resolution.

Also, please update the language reference with the relevant implemented features from the spec (basically copy from here to here.

I would also add a list of follow up items in the pull request with tracking issues.

examples/tests/valid/struct_json_conversion.w Outdated Show resolved Hide resolved
libs/wingcompiler/src/compile.ts Outdated Show resolved Hide resolved
libs/wingsdk/src/shared/bundling.ts Outdated Show resolved Hide resolved
libs/wingsdk/src/std/struct.ts Show resolved Hide resolved
@hasanaburayyan hasanaburayyan force-pushed the hasan/struct-conversion-almost-there branch from 6915625 to 0b764ca Compare August 8, 2023 01:01
@hasanaburayyan
Copy link
Contributor Author

Also, please update the language reference with the relevant implemented features from the spec (basically copy from here to here.

@eladb forgot to update the docs before I re-requested review. Added as a todo but will complete it in the morning.

@hasanaburayyan hasanaburayyan added the 🚧 pr/do-not-merge PRs with this label will not be automatically merged by mergify. label Aug 8, 2023
@hasanaburayyan
Copy link
Contributor Author

Added do not merge label until I complete the documentation and issue tracking todos

Copy link
Contributor

@eladb eladb left a comment

Choose a reason for hiding this comment

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

Hey!

This is amazing and I know you are keen to get this over the finish line, but there are a few tweaks I think we should make.

The generated struct code and the interaction between it and the std.Struct seem a bit convoluted.

I imagined something like;

Foo.Struct.js

class Foo {
  static get schema() {
    // return a full self-contained json schema, including all nested structs...
  }

  static fromJson(x) {
    return std.Struct.validate(x, this.schema);
  }

  // lifting boilerplate 

}

Something along these lines. KISS...

@eladb
Copy link
Contributor

eladb commented Aug 10, 2023

I think Im going to go ahead and leave this PR open and just add the remaining features for the issue rather than split them into a followup pr

That's usually something I regret, especially with a big project like this... I would try to get this merged first and follow up with subsequent PRs.

hasanaburayyan and others added 4 commits August 11, 2023 10:37
Signed-off-by: monada-bot[bot] <monabot@monada.co>
Signed-off-by: monada-bot[bot] <monabot@monada.co>
@hasanaburayyan hasanaburayyan force-pushed the hasan/struct-conversion-almost-there branch from 1e55669 to cd67322 Compare August 11, 2023 17:35
@hasanaburayyan hasanaburayyan force-pushed the hasan/struct-conversion-almost-there branch from d3ab970 to 36b651d Compare August 11, 2023 18:01
Signed-off-by: monada-bot[bot] <monabot@monada.co>
Copy link
Contributor

@eladb eladb left a comment

Choose a reason for hiding this comment

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

LGTM. @yoav-steinberg / @Chriscbr / @MarkMcCulloh please give the final approval

libs/wingc/src/type_check.rs Outdated Show resolved Hide resolved
libs/wingsdk/src/std/struct.ts Outdated Show resolved Hide resolved
monadabot and others added 2 commits August 11, 2023 18:46
Signed-off-by: monada-bot[bot] <monabot@monada.co>
monadabot and others added 2 commits August 11, 2023 19:38
Signed-off-by: monada-bot[bot] <monabot@monada.co>
Copy link
Contributor

@MarkMcCulloh MarkMcCulloh left a comment

Choose a reason for hiding this comment

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

🎉

libs/wingc/src/type_check/jsii_importer.rs Outdated Show resolved Hide resolved
libs/wingc/src/type_check.rs Outdated Show resolved Hide resolved
Copy link
Contributor

@MarkMcCulloh MarkMcCulloh left a comment

Choose a reason for hiding this comment

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

🎉

@hasanaburayyan hasanaburayyan removed 🚧 pr/do-not-merge PRs with this label will not be automatically merged by mergify. ⚠️ pr/review-mutation PR has been mutated and will not auto-merge. Clear this label if the changes look good! labels Aug 12, 2023
@mergify
Copy link
Contributor

mergify bot commented Aug 12, 2023

Thank you for contributing! Your pull request will be updated from main and then merged automatically (do not update manually, and be sure to allow changes to be pushed to your fork).

mergify bot added a commit that referenced this pull request Aug 12, 2023
@mergify mergify bot merged commit a930aa4 into main Aug 12, 2023
11 checks passed
@mergify mergify bot deleted the hasan/struct-conversion-almost-there branch August 12, 2023 23:05
@monadabot
Copy link
Contributor

Congrats! 🚀 This was released in Wing 0.25.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Implement Struct.tryFromJson Json: schema validation and assignment to struct
6 participants