Skip to content

Handling of circular refs in spec is broken #293

Closed

Description

@magicmatatjahu

TL;DR;

Handling of circular refs in spec is broken and we should fix it.

Describe the bug

Currently our parser handle circular refs. In opinion the result is invalid:

  • we handle very simple cases, only properties for object type and we marked every "circular" items as circular, what is not a valid. Readme.md says:

    x-parser-circular property is added to every schema of array type that is circular. To check if schema is circular or not, you should use isCircular() function on a Schema model like document.components().schema('RecursiveSelf').properties()['selfChildren'].isCircular().

  • we don't handle circular refs in combined schemas (see Circular reference causes a "Template render error" error html-template#165),

  • we don't handle very complex cases (see Circular references causes stack overflow html-template#67) - it's probably not related to circular refs, but we should also support $ref: # case 😄.

Why I have a problem with "circular" items? See the schema, which we use in tests:

    RecursiveSelf:
      type: object
      properties:
        selfChildren:
          type: array
          items:
            $ref: '#/components/schemas/RecursiveSelf'
        selfObjectChildren:
          type: object
          properties:
            test:
              $ref: '#/components/schemas/RecursiveSelf'
            nonRecursive:
              type: string
        selfSomething:
          type: object
          properties:
            test: 
               $ref: '#/components/schemas/RecursiveAncestor'
    RecursiveAncestor:
      type: object
      properties:
        ancestorChildren:
          type: array
          items:
            $ref: '#/components/schemas/RecursiveSelf'
        ancestorSomething:
          type: string

In parsing we mark RecursiveAncestor.properties.ancestorChildren as circular. This is due to the fact that when checking cyclic references in RecursiveAncestor we go to RecursiveSelf schema and we see RecursiveAncestor in RecursiveSelf.properties.selfSomething.properties.test. And this is correct only for RecursiveSelf schema, not for RecursiveAncestor! We save x-parser-circular extension to original reference of RecursiveAncestor not to copy of it, so by this non cyclic schema is marked as cyclic. Imagine that we render RecursiveAncestor and by isCircular() function we have information that RecursiveAncestor.properties.ancestorChildren.items is circular. It's true in RecursiveSelf point of view, not in RecursiveAncestor, because here we have relationship:

RecursiveAncestor -> RecursiveSelf -> RecursiveAncestor

so this is exactly circular reference in RecursiveAncestor case, which we should mark in some way. We must think in this problem like exactly circular references works in programming languages. If you will try log the RecursiveAncestor object you will see something like:

<ref *1> RecursiveAncestor
  - properties
    - ancestorChildren
      - items <ref *2> RecursiveSelf
        - properties
          - selfChildren 
            - items <ref *2> RecursiveSelf
          - selfObjectChildren 
            - properties 
              - test <ref *2> RecursiveSelf
          - selfSomething 
            - properties 
              - test <ref *1> RecursiveAncestor

so you have circular references in second deep, not in first as works it currently.

Also mark schemas if items is "circular" (which don't have to be a circular as mentioned above) is not a good idea in the other hand. items can be also described as array (tuple type) of schemas. So having schema like:

RecursiveItems:
  items: 
    - type: string
    - $ref: '#/components/schemas/RecursiveItems'

as developer, I should know that exactly 1 index of items is circular, not whole schema :)

Using JSON Schema 07-draft (and upper) we can also write this beast:

   RecursiveComplex:
      type: [object, array]
      patternProperties:
        ^foo: 
          $ref: '#/components/schemas/RecursiveSelf'
        ^bar: 
          type: string
      contains:
        $ref: '#/components/schemas/RecursiveComplex'
      items:
        - type: string
        - $ref: '#/components/schemas/RecursiveComplex'
      if:
        $ref: '#/components/schemas/RecursiveAncestor'
      then:
        $ref: '#/components/schemas/RecursiveComplex'

using another keywords reserved for object and array, so also x-parser-circular-props doesn't fully fulfill its task.

What is exactly circular here? :) I see:

RecursiveComplex -> ^foo -> RecursiveSelf -> selfChildren -> items // and another properties from RecursiveSelf
RecursiveComplex -> contains -> RecursiveComplex
RecursiveComplex -> items[1] -> RecursiveComplex
RecursiveComplex -> if -> RecursiveAncestor -> ancestorChildren -> items -> RecursiveSelf -> selfChildren -> items // ...etc
RecursiveComplex -> then -> RecursiveComplex

Some people can say: This is not a logical valid, we shouldn't handle this. If we add possibility (by JSON Schema) to developer to write schemas like this, we should also try handle them.

Task is not trivial and we should try to define how to mark circular refs in another way (yes, breaking change, because currently idea doesn't work as expected) to handle all the possible cases. Probably we should "create" copy of some parts of parsed spec and mark these parts as circular by x-parser-circular extension.

How to Reproduce

Just see the tests -> https://github.com/asyncapi/parser-js/blob/master/test/parse_test.js#L568 RecursiveAncestor references is marked as circular but it's incorrect. There should be marked as circular the path:

RecursiveAncestor -> ancestorChildren -> items -> selfSomething -> test (which is RecursiveAncestor)

Expected behavior

Handling of circular refs should be generic and works with any cases, not only for properties in object and "circular" items, but also for other JSON Schema keywords.

Activity

  1. added
    bug
    on Apr 25, 2021
  2. derberg commented on Apr 26, 2021

    @derberg
    Member

    Hey, can you modify this issue a bit as I'm afraid it is touching 2 different topics, in the main description you're focused on explaining the bug, and then in expected behavior section you talk about a new feature.

    • I suggest you move the proposed feature to a separate task as it has nothing to do with the bug
    • Please provide expected behavior in the way that it is easy for anyone to pics up and understand the issue. So basically take your example schema, put it side by side with how schema will look like after parsing now (where and how extensions are added) and how it should look like in your opinion
  3. magicmatatjahu commented on Apr 26, 2021

    @magicmatatjahu
    MemberAuthor

    @derberg For me, the lack of support for circular references in extensions is a bug (they can also be used in schemes, so it should be supported), but okay, I'll make a separate issue with a description of what it should look like for bindings and extensions, btw. the same way as for the scheme.

  4. derberg commented on Apr 26, 2021

    @derberg
    Member

    lack of support != bug 😄
    when I worked on it, the intention was to have it for schemas. When we add support for extensions and bindings, it will be feat: not fix:

  5. github-actions commented on Jun 26, 2021

    @github-actions

    This issue has been automatically marked as stale because it has not had recent activity 😴
    It will be closed in 60 days if no further activity occurs. To unstale this issue, add a comment with detailed explanation.
    Thank you for your contributions ❤️

  6. github-actions commented on Aug 28, 2021

    @github-actions

    This issue has been automatically marked as stale because it has not had recent activity 😴
    It will be closed in 60 days if no further activity occurs. To unstale this issue, add a comment with detailed explanation.
    Thank you for your contributions ❤️

  7. magicmatatjahu commented on Oct 15, 2021

    @magicmatatjahu
    MemberAuthor

    I think I managed to figure out how to solve the problem with circular references throughout our document, and surprisingly it is not that difficult, but it requires a fix in the Base model class.

    Before I go into the proposal, I'll give an example of a scheme (very complex) and describe what is circular.

    {
      RecursiveSelf: {
        properties: {
          selfChildren: '#/RecursiveSelf',
          selfObjectChildren: {
            properties: {
              test: '#/RecursiveSelf',
              nonRecursive: {
                type: "string"
              }
            }
          },
          selfSomething: {
            properties: {
              test: '#/RecursiveAncestor',
            }
          }
        }
      },
      RecursiveAncestor: {
        properties: {
          ancestorChildren: '#/RecursiveSelf',
          ancestorSomething: {
            type: "string"
          }
        }
      },
      RecursiveComplex: {
        patternProperties: {
          "^foo": '#/RecursiveSelf',
        },
        contains: '#/RecursiveComplex',
        if: '#/RecursiveAncestor'
      },
      RecursiveArray: [
        '#/RecursiveSelf',
        {
          properties: {
            items: '#/RecursiveArray',
          }
        }
      ],
      Root: '#',
      NestedRoot: {
        properties: {
          items: '#',
          properties: {
            prop: '#',
          },
        }
      },
      Property: '#/RecursiveSelf',
      NestedProperty: {
        properties: {
          prop: '#/RecursiveSelf',
        }
      },
    }

    What I see what is circular - gives the json pointer notation, the key is the value where the circular occurs and the key value is the object that is circular relative to the key:

    '$.RecursiveSelf.properties.selfChildren' -> '$.RecursiveSelf',
    '$.RecursiveSelf.properties.selfObjectChildren.properties.test' -> '$.RecursiveSelf',
    '$.RecursiveSelf.properties.selfSomething.properties.test.properties.ancestorChildren' -> '$.RecursiveSelf',
    '$.RecursiveAncestor.properties.ancestorChildren.properties.selfChildren' -> '$.RecursiveAncestor.properties.ancestorChildren',
    '$.RecursiveAncestor.properties.ancestorChildren.properties.selfObjectChildren.properties.test' -> '$.RecursiveAncestor.properties.ancestorChildren',
    '$.RecursiveAncestor.properties.ancestorChildren.properties.selfSomething.properties.test' -> '$.RecursiveAncestor',
    ...
    

    I think the first two items are understandable - RecursiveSelf is circular in these areas, but the third item may seem strange. It goes to the RecursiveAncestor object and then indicates that the circular object is in ancestorChildren prop.

    But what about 4-6 elements. They show that we have 3 circular elements. First two is for RecursiveSelf element, but relative to the $.RecursiveAncestor.properties.ancestorChildren object - here we look at the circularity with respect to RecursiveAncestor object and not RecursiveSelf like the previous one. The 6th element shows circularity with respect to $.RecursiveAncestor - we start with RecursiveAncestor and end with $.RecursiveAncestor.

    Here is the whole scheme with all circular items - see that the circularity against root is also checked:

    '$.RecursiveSelf.properties.selfChildren' -> '$.RecursiveSelf',
    '$.RecursiveSelf.properties.selfObjectChildren.properties.test' -> '$.RecursiveSelf',
    '$.RecursiveSelf.properties.selfSomething.properties.test.properties.ancestorChildren' -> '$.RecursiveSelf',
    '$.RecursiveAncestor.properties.ancestorChildren.properties.selfChildren' -> '$.RecursiveAncestor.properties.ancestorChildren',
    '$.RecursiveAncestor.properties.ancestorChildren.properties.selfObjectChildren.properties.test' -> '$.RecursiveAncestor.properties.ancestorChildren',
    '$.RecursiveAncestor.properties.ancestorChildren.properties.selfSomething.properties.test' -> '$.RecursiveAncestor',
    '$.RecursiveComplex.patternProperties.^foo.properties.selfChildren' -> '$.RecursiveComplex.patternProperties.^foo',
    '$.RecursiveComplex.patternProperties.^foo.properties.selfObjectChildren.properties.test' -> '$.RecursiveComplex.patternProperties.^foo',
    '$.RecursiveComplex.patternProperties.^foo.properties.selfSomething.properties.test.properties.ancestorChildren' -> '$.RecursiveComplex.patternProperties.^foo',
    '$.RecursiveComplex.contains' -> '$.RecursiveComplex',
    '$.RecursiveComplex.if.properties.ancestorChildren.properties.selfChildren' -> '$.RecursiveComplex.if.properties.ancestorChildren',
    '$.RecursiveComplex.if.properties.ancestorChildren.properties.selfObjectChildren.properties.test' -> '$.RecursiveComplex.if.properties.ancestorChildren',
    '$.RecursiveComplex.if.properties.ancestorChildren.properties.selfSomething.properties.test' -> '$.RecursiveComplex.if',
    '$.RecursiveArray[0].properties.selfChildren' -> '$.RecursiveArray[0]',
    '$.RecursiveArray[0].properties.selfObjectChildren.properties.test' -> '$.RecursiveArray[0]',
    '$.RecursiveArray[0].properties.selfSomething.properties.test.properties.ancestorChildren' -> '$.RecursiveArray[0]',
    '$.RecursiveArray[1].properties.items' -> '$.RecursiveArray',
    '$.Root' -> '$',
    '$.NestedRoot.properties.items' -> '$',
    '$.NestedRoot.properties.properties.prop' -> '$',
    '$.Property.properties.selfChildren' -> '$.Property',
    '$.Property.properties.selfObjectChildren.properties.test' -> '$.Property',
    '$.Property.properties.selfSomething.properties.test.properties.ancestorChildren' -> '$.Property',
    '$.NestedProperty.properties.prop.properties.selfChildren' -> '$.NestedProperty.properties.prop',
    '$.NestedProperty.properties.prop.properties.selfObjectChildren.properties.test' -> '$.NestedProperty.properties.prop',
    '$.NestedProperty.properties.prop.properties.selfSomething.properties.test.properties.ancestorChildren' -> '$.NestedProperty.properties.prop'
    

    If anyone does not understand that (or something is broken), please write :)

    My suggestion:

    • save object above with circular references saved as json pointer in x-parser-circular-refs in the root of parsed AsyncAPI document.
    • update Base model class to:
    class Base {
      constructor (json, {
        asyncapi, // parsed AsyncAPI document
        parent, // parent element, for example - for example `ExternalDocs` model created by `.info` path will have `Info` instance as parent
        path, // json pointer of given element - for example `externalDocs` created in `.info` path will have value `$.info.externalDocs`
      }) {
        ...
      }
    
      // check if given element is circular using `x-parser-circular-refs` of asyncapi doc
      isCircular(): boolean {
        const circularRefs = asyncapi.ext(`x-parser-circular-refs`);
        // check if `x-parser-circular-refs` has path of given element, if yes element is circular
        if (circularRefs.hasOwnProperty(this.path)) {
          return true;
        }
        return false;
      }
    
      // get circular element of given element
      getCirularObject(): any {
        if (this.isCircular() === false) {
          return;
        }
    
        const circularRefs = asyncapi.ext(`x-parser-circular-refs`);
        const circularRefPath = circularRefs[this.path];
        if (circularRefPath === undefined) {
          return;
        }
    
        let el = this.parent;
        while (el && el.path !=== circularRefPath) {
          el = el.parent;
        }
        return el;
      }
    }

    Notes:

    What do you think? The solution is not as complicated as it seems, just parsing and mapping the circular elements takes 30 lines (I have worked POC), more work will be done with passing the parents and paths in the elements, so we will have to update each model constructor.

    cc @derberg @jonaslagoni @fmvilas @boyney123 @smoya if you are not interested in the topic, you don't have to write back, but maybe it will interest you :)

  8. magicmatatjahu commented on Oct 15, 2021

    @magicmatatjahu
    MemberAuthor

    I came up with another way, a simpler one based only on the parent object in Schema model that creates the given model:

    class Schema {
      constructor (json, {
        parent,
      }) {
        ...
      }
    
      // check if given element is circular using parent elements
      isCircular(): boolean {
        let el = this.parent;
        while (el) {
          if (el.json() === this.json()) return true;
          el = el.parent;
        }
        return false
      }
    }

    Compared to the first solution is less optimal because we have to check the whole sequence of downward parents, while in the first solution we check the circularity once and use the information.

  9. m-wild commented on Oct 17, 2021

    @m-wild

    Hi there, seems this has been partially resolved in the react/ui repo, hope this is the right place to raise the issue :)

    It seems that this is not yet supported when the recursive reference is a oneOf item.

    Broken:

    components:
      schemas:
        exception:
          id: exception
          type: object
          properties:
            Message:
              type: string
            InnerException:
              oneOf:
                - type: 'null'
                - $ref: '#/components/schemas/exception'

    Working:

    components:
      schemas:
        exception:
          id: exception
          type: object
          properties:
            Message:
              type: string
            InnerException:
              type: object
              $ref: '#/components/schemas/exception'
  10. Tenischev commented on Nov 14, 2021

    @Tenischev
    Contributor

    Hi. I faced an issue during testing fix for asyncapi-archived-repos/java-spring-template#150
    if I provide such schema for parser:

    components:
      messages:
        lightMeasured:
          summary: Inform about environmental lighting conditions for a particular streetlight.
          payload:
            $ref: "#/components/schemas/lightMeasuredPayload"
      schemas:
        lightMeasuredPayload:
          type: object
          properties:
            lumens:
              type: integer
              minimum: 0
              description: Light intensity measured in lumens.
            childs:
              type: array
              items:
                $ref: "#/components/schemas/lightMeasuredPayload"
    

    It returns three messages instead of one, these two extra messages will be anonymous and just copy of normal one - lightMeasured:

    anonymous-message-1                                                                                                  
    Message {
      _json: {
        schemaFormat: 'application/vnd.aai.asyncapi;version=2.0.0',
        'x-parser-message-parsed': true,
        summary: 'Inform about environmental lighting conditions for a particular streetlight.',
        payload: {  
          type: 'object',    
          properties: [Object],   
          'x-parser-schema-id': 'lightMeasuredPayload'
        },
        'x-parser-original-schema-format': 'application/vnd.aai.asyncapi;version=2.0.0',   
        'x-parser-original-payload': {  
          type: 'object', 
          properties: [Object],             
          'x-parser-schema-id': 'lightMeasuredPayload' 
        },
        'x-parser-message-name': '<anonymous-message-1>' 
      }
    }                                                                                                                      
    anonymous-message-2
    Message {
      _json: {
        schemaFormat: 'application/vnd.aai.asyncapi;version=2.0.0',
        'x-parser-message-parsed': true,
        summary: 'Inform about environmental lighting conditions for a particular streetlight.',   
        payload: {
          type: 'object',
          properties: [Object],
          'x-parser-schema-id': 'lightMeasuredPayload' 
        },
        'x-parser-original-schema-format': 'application/vnd.aai.asyncapi;version=2.0.0', 
        'x-parser-original-payload': { 
           type: 'object', 
           properties: [Object],
           'x-parser-schema-id': 'lightMeasuredPayload' 
        },
        'x-parser-message-name': '<anonymous-message-2>' 
      }
    }
    lightMeasured
    Message {
      _json: {
        summary: 'Inform about environmental lighting conditions for a particular streetlight.', 
        payload: {
          type: 'object',
          properties: [Object],
         'x-parser-schema-id': 'lightMeasuredPayload'
        },
        'x-parser-original-schema-format': 'application/vnd.aai.asyncapi;version=2.0.0',
        'x-parser-original-payload': {
          type: 'object',
          properties: [Object],
          'x-parser-schema-id': 'lightMeasuredPayload' 
        },
        schemaFormat: 'application/vnd.aai.asyncapi;version=2.0.0',
        'x-parser-message-parsed': true,
        'x-parser-message-name': 'lightMeasured' 
      }
    }                        
    
  11. asyncapi-bot commented on Nov 23, 2021

    @asyncapi-bot
    Contributor

    🎉 This issue has been resolved in version 1.12.0 🎉

    The release is available on:

    Your semantic-release bot 📦🚀

  12. magicmatatjahu commented on Jan 3, 2022

    @magicmatatjahu
    MemberAuthor

    @tehmantra Very sorry, I saw these comments only now. We published new generator/html-template/react-component with supporting of circular refs. Could you check if everything works already in your cases? I would appreciate it :)

  13. magicmatatjahu commented on Jan 3, 2022

    @magicmatatjahu
    MemberAuthor

    @Tenischev Hello! Very sorry, I saw these comments only now. Hmm 🤔 I am not sure if it is related to circular references, but I improved the traverse of the schemas in the parser and maybe the latest version of generator/parser solved the problem. Could you please check?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugreleased

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions