Skip to content

Support JSON Schema validation #5494

Open

Description

@segphault

As we've discussed a few times, it'd be really nice for RethinkDB to natively support JSON Schema validation. Possibly, this feature could be exposed through a new ReQL term that could be used in conjunction with others like r.branch to make operations conditionally depend on validation.

Handling Refs

One of the most complex issues to address in JSON Schema implementations is handling references. A reference, signified by the $ref key, allows a JSON Schema to point to another document or node that the validator should use in its place. When writing JSON Schemas, you typically structure it in parts that you can reference in order to maximize reuse.

In conventional schemas, references either:

  • Point to another node in the same document
  • Point to another document entirely, using a URL

Assuming that schemas are stored in RethinkDB like any other JSON document, we'd need a way for the documents to reference other documents stored in the database. Ideally, something like the proposed document reference pseudotype could address this issue.

It might be easier, in the short term, to make it so that the schema validation ReQL term can optionally take an anonymous function with a ReQL expression that specifies how to resolve references.

There are some major wrinkles that make it difficult to simply walk the tree and replace $ref nodes with the content that they specify. Most notably, it's common to use mutually recursive schemas to model a structure with potentially infinite depth. It's important for JSON Schema implementations to support that common pattern without choking.

Failure modes

Users might want to have the option of enabling some alternate behaviors aside from basic failure when a document doesn't validate against a schema. These are two that come to mind as being particularly useful:

  • Strip properties that don't conform with the schema
  • Automatically coerce data types in cases where a property value has the wrong type

Programmatic validation rules

Some popular JSON Schema implementations give users a way to define their own custom validation keywords with programmatic validation rules. Although perhaps not needed in the first pass, it might eventually be nice to support this feature, allowing custom validation functions to be implemented with either ReQL, JavaScript (executed using the same engine as r.js), or both.

Valijson

The open source valijson library could be a useful starting point for implementing JSON Schemas in RethinkDB. It is BSD-licensed and supports RapidJSON.

In valijson, you can provide a callback that it will use to resolve references, but the feature is still classified as experimental. In order to avoid the recursion trap, it invokes the callback as needed during validation rather than while it is building the schema. As described in the readme, there's a branch where the developer is working on a two-pass schema loader that will hopefully improve the situation.

Activity

  1. danielmewes commented on Mar 9, 2016

    @danielmewes
    Member

    Nice writeup @segphault . I have to look into this in a bit more detail.

    I should note that we cannot actually ensure referential (cross-document) integrity. We can check those criteria on a "best effort" basis, but they will always be subject to race conditions.

  2. added this to the subsequent milestone on Mar 9, 2016
  3. danielmewes commented on Mar 9, 2016

    @danielmewes
    Member

    I'm going to put this into subsequent for now.

    I think there are a bunch of open questions here that make it more reasonable to implement this in Horizon for now, mostly because we are more flexible there when it comes to amending and changing how schema validation works at a later point.

    Long term though I think this should definitely be a core RethinkDB feature. A JSON schema term would work great as a per-table validation function, as proposed in #4210 .

  4. thelinuxlich commented on Mar 11, 2016

    @thelinuxlich

    Just as an inspiration, I'm using Joi(https://github.com/hapijs/joi) which provides a DSL similar to ReQL to validate schema rules and also return the final object with the types correctly coerced.

    Take a look into a schema I'm using in production: https://gist.github.com/thelinuxlich/5d0b8dcb1a5a791838dc

    I import this into a authorization middleware and execute Joi.validate(params, schema). Then I can rest assured that nothing strange gets saved into RethinkDB documents.

  5. mbroadst commented on Jul 5, 2016

    @mbroadst
    Contributor

    Hey, so I put together this fork of thinky called thinkagain which supports json-schema as its model definition format. The more I work through my projects using rethinkdb, the more I think I wouldn't need the ODM at all if I could get validation on the driver/database level. I'm very much in support of this proposal, but I wonder if an interesting first step might be to develop an exploratory fork of the JS driver (or more likely rethinkdbdash) that implements support for schemas. I think this could help out with #5879 as well.

    Would anybody be interested in this, or more importantly helping me out with this?

  6. mbroadst commented on Jul 6, 2016

    @mbroadst
    Contributor

    On another line of discussion, I would also totally be willing to investigate preliminary support for json-schema in rethinkdb itself. Is there hesitation to add this support because of a desire to have complete support or nothing at all?

    @danielmewes couldn't we start off with support for just table validations (no references, or customization), storing the json-schema in e.g. table_config if you did something like r.table('mytable').schema({ some: { json: 'schema' } }) ? I've already worked out the json-schema for custom reql types (all the geo types, dates, etc) in thinkagain, so those could be baked in and leveraged.

  7. danielmewes commented on Jul 7, 2016

    @danielmewes
    Member

    @mbroadst I think there's value in having a version without references and other advanced features. However we should carefully discuss the API so that it's flexible enough.

    The simplest option for an API I can think of is adding a top-level r.checkJsonSchema(schema, object) -> bool command. Then you could call this function in a write hook ( #5813 ) and fail writes that don't adhere to the schema. The schema itself would be stored as a constant within the write hook function, and no additional changes to the table metadata etc. would be required.

    A disadvantage of this is that it might be a bit too complicated to set up and manage. Something closer to what you suggest, where we add a new "schema" property to the table configuration is probably clearer and closer to what users expect.

  8. marshall007 commented on Jul 7, 2016

    @marshall007
    Contributor

    @mbroadst and I were discussing this in Slack. We came to the conclusion that it probably makes the most sense to implement something like the r.schema(...) term proposed in #5879. As a first pass, I think we should slightly modify that proposal to only accept a json-schema and return a function that validates an object/expression. We can perhaps flesh out a fluent API for building schemas, but after discussing things with @mbroadst I think it's better that we start by relying on an existing standard and perhaps build upon that later.

    We see this as a good first step since it gives us an immediately useful and testable ReQL term. Having a schema primitive on the server also provides a clear path for incorporating schemas elsewhere (i.e. as write hooks, expiration functions, secondary indices, table schemas, etc).

    @danielmewes what are your thoughts on getting something like this in for 2.4.x or 2.5?

  9. danielmewes commented on Jul 7, 2016

    @danielmewes
    Member

    That sounds pretty reasonable to me (though I'd like to send it through a full discussion round with the rest of the team to finalize the API). 2.4 is already pretty full, but I think this is a realistic goal for 2.5.

  10. mbroadst commented on Jul 7, 2016

    @mbroadst
    Contributor

    @danielmewes I'm willing to do the initial POC work on it, this would be a great boon for my particular use case. Eager to hear what the rest of the team thinks about the idea, so maybe we can chat on slack when you have consensus?

  11. mbroadst commented on Jul 12, 2016

    @mbroadst
    Contributor

    Hey everybody, just wanted to chime in with an update from my side. I've implemented incredibly rudimentary support for json-schema in this commit over here: mbroadst@cf59ca5. I'm hoping this can serve as a platform for discussion around the proposed feature.

    Presently json-schema support is implemented through a r.schema pseudo-type, as well as a r.validate operation (which operates on datum). This looks like:

    r.expr({ first: 'matt', last: 'broadstone' })
      .validate(r.schema({
        type: 'object', 
        required: [ 'first', 'last' ],
        properties: { first: { type: 'string' }, last: { type: 'string' } }
      }))
    

    Schema validation is provided through rapidjson presently (rapidjson was updated to v1.0.2 in the previous two commits on that branch), though the implementation details I think are less important for this discussion. Suffice to say it's highly desirable in the future that the validation occurs explicitly on datum_t rather than a need to convert to and from rapidjson's Value type.

    As previously mentioned, I think targeting the simplest use cases first is a great first step in this effort. To that end I'm not sure that discussion of references, and shared definitions is particularly in scope at this point. Beyond that, I'm quite eager to hear your opinions on the topic!

    UPDATE: I guess I should mention one other thing: For support for ReQL-specific types, I have a few existing validation schemas written up for thinkagain already over here: https://github.com/mbroadst/thinkagain/tree/master/lib/types. These could be baked in to the server to provide validation support for them out of the box. Unfortunately since the spec strictly uses json types, these need to be referred to using $ref - so that might be a starting place for the ref discussion.

    UPDATE: Added support for r.validate(r.schema, datum), as well as r.schema().validate(datum)

  12. mbroadst commented on Sep 2, 2016

    @mbroadst
    Contributor

    Very excited to see that write hooks were merge into next, only to realize that we haven't moved forward with this conversation at all. Ping everybody? 😄

  13. 10 remaining items

  14. marshall007 commented on Sep 8, 2016

    @marshall007
    Contributor

    Would be pretty neat to have the Web UI pull in table schemas to inform the Data Explorer with additional/smarter completion. Even something super basic to start like always autocompleting r.row and bracket terms (ignoring their context) with fields in the schema for the table in the current query would go a long way.

  15. segphault commented on Sep 9, 2016

    @segphault
    Author
    • For table-level schema validation, I favor option 2
    • I think type coercion should not happen by default, but it'd be nice to have an optarg for this. Also an optarg that lets you choose whether additional properties are merely stripped versus causing validation failure
    • For psuedotypes, I think $ref is the correct approach. We should have standard names for our RethinkDB psuedotypes that you can use in a $ref
    • I don't think migration is strictly necessary. I definitely think it should be possible to modify documents in ways that don't conform with the schema. In fact, it might even be useful to have optargs for write operations that tell RethinkDB to bypass the schema for a given operation

    I'm pretty excited to see this moving forward. 👍

  16. chrisvariety commented on Sep 9, 2016

    @chrisvariety

    @segphault FYI additionalProperties is built into JSON-schema and does... exactly what you would expect, so I think that base is covered!

  17. marshall007 commented on Sep 9, 2016

    @marshall007
    Contributor

    @segphault the problem with using $ref for pseudotypes is that it will bomb on json-schema clients that don't support overloading the behavior of that attribute. On the other hand, format is supposed to be ignored when the client doesn't support the attribute and/or keyword. Per spec:

    A format attribute can generally only validate a given set of instance types. If the type of the instance to validate is not in this set, validation for this format attribute and instance SHOULD succeed.
    ...
    Implementations MAY add custom format attributes. Save for agreement between parties, schema authors SHALL NOT expect a peer implementation to support this keyword and/or custom format attributes.

    format definitely offers the most flexibility for users in defining their schema and portability across client implementations.

  18. segphault commented on Sep 9, 2016

    @segphault
    Author

    @chrisvariety yep, I'm aware of additionalProperties. The suggestion that I was making has to do with how it's handled. When additionalProperties is set to false, the default behavior of a schema validator is to say that the object is invalid. What I'd like is an option that makes it so that it will still treat the object as valid but prune the extra properties. This is similar to the data filtering feature in ajv: https://github.com/epoberezkin/ajv#filtering-data Sorry if I wasn't clear!

    @marshall007 that's a fair point, and I can see how using format would simplify portability. On the other hand, I think that publishing schemas that describe the psuedotypes is a more idiomatic approach for JSON schema. Schema $refs can resolve URLs, so we can put an official schema somewhere as a path on rethinkdb.com and most other implementations would hopefully be able to still seamlessly take advantage of it. Granted, I don't know how ubiquitously URL $refs are actually used in practice.

  19. mike-marcacci commented on Sep 9, 2016

    @mike-marcacci

    the problem with using $ref for pseudotypes is that it will bomb on json-schema clients that don't support overloading the behavior of that attribute

    @marshall007 could you expand a bit on this? I am leaning towards $ref, because all RQL pseudotypes are in fact valid JSON objects, and it seems perfectly normal to define them in an external schema that's officially provided by rethinkdb.

    The problem with using format is the "agreement between parties" part: even if the format names were namespaced, you're essentially defining "global" formats, and the configuration is entirely out-of-channel.

    If these types were implemented as references, on the other hand, there wouldn't be anything non-standard.

  20. mbroadst commented on Sep 9, 2016

    @mbroadst
    Contributor
    • for table-level validation I prefer (1) with a possible future addition of (3). I think adding the convenience specialization for the write hook doesn't actually provide that much convenience (users are at most doing this once-per-table), and makes the write hook implementation less "pure". Is there any added benefit I'm missing from going with option (2) here?
    • totally agree that type coercion should not be enabled by default, but definitely should be an opt-arg, and the ajv coercion rules are a very good place to start.
    • In fact, there are a number of options that ajv supports that could be beneficial opt-args here: useDefaults (fills in default values => maps to default reql term), removeAdditional (remove properties not defined in the schema, I think this satisfies @segphault 's request above?), etc.
    • also totally agree with r.schema vs r.model, signals intent better.
    • I also think format is definitely the best option for informing the RethinkDB side of the validation equation. As @marshall007 pointed out earlier, ajv does not presently support format on non-strings, but that is being discussed over here and I think this could be an interesting use-case for pushing that support forward. In this regard format could be used to give type info to RethinkDB for coercion purposes (as well as internal representation), and would otherwise gracefully reduce in the case that libraries that don't support the given format.
      • Another consideration I would like to bring up would be the possibility of using custom keywords. We could support reql types using such a keyword instead of format, e.g.reql_type: 'date'. This could lead to some flexibility considering that the any type for json-schema v4 is simply the "empty schema" ({}). For example, s schema defined as { reql_type: 'date' } would not technically cause a validation failure in the event that another implementation hasn't defined the custom keyword, as it would gracefully degrade into the empty schema. Not suggesting this is the way to go, but just pointing out the feature.
      • Additionally, I think that adding custom type values is an absolute non-starter, as it will break spec.
    • @segphault and @mike-marcacci, I think you guys are sort of half-correct here. $ref should indeed be used for pseudo-types (we can rip them right from thinkagain tbh), however I believe format (or reql_type?) should still be used for additional contextual type information. Figuring out how the user wants to send/receive a Date is a very good case: it can be a Number (epoch time), Object (pseudotype with internal Number), strings in various formats (rfc3339 etc). RethinkDB is going to need help figuring out exactly what they want to accept in this case and I think format can help here given it's flexibility.
    • Another thing I would like to track is that I believe the validation should support either a "bail on first error" or "return all errors" mode. The former is generally implemented by people writing parsers, while the latter is incredibly useful for client side purposes.
    • I agree that migration is something that should be a possibility in the future, but perhaps is out-of-scope for an initial implementation. To that end I would prefer option (1) here.
  21. marshall007 commented on Sep 9, 2016

    @marshall007
    Contributor

    @mike-marcacci yea so the issue is that for date, binary, and geo types, it is rare that you'd want to perform client-side validation of the ReQL pseudotype representation. In the case of dates, you're gonna need different behavior in the browser, server-side, and database. The idea is that you should be able to use the exact same json-schema everywhere in your stack and across applications/languages.

    @mbroadst elaborated the point well. The user should be specifying the types they're working with in the client without worrying about how the database represents them internally. Furthermore, $ref does not degrade gracefully in terms of client support. You have no real guarantees that your client can side-load named schemas ahead of time or fetch remote schemas (offline, strict Content-Security policies, etc).

    By using format, clients have well-defined behavior by default (no-op), unless the user explicitly implements behavior by using a client that supports doing so.

  22. marshall007 commented on Sep 9, 2016

    @marshall007
    Contributor

    @segphault so to clarify, even if your client was able to seamlessly integrate the $ref schema, that's not even necessarily what you want to be validating against in a given context.

  23. segphault commented on Sep 9, 2016

    @segphault
    Author

    Ah yes, I think I understand the issue now. Particularly with date/time values which get translated to and from language-native types, I can see why it wouldn't be practical to try to validate that on the client side using a schema for the database's representation. Thanks for the clarification. I can see why you would need to use format to address that.

  24. mike-marcacci commented on Sep 9, 2016

    @mike-marcacci

    Hmm, I do see the issue here, but having built a few projects that are heavily driven by json-schema, I had to abandon using format to solve the date issue in particular. The problem arises from the fact that your document is not just json-encoded between the database and server, but again between the server and client – you do ultimately need to build a mechanism for encoding these "special" types between the client and server, and this intermediate form is the one that must be validated.

    EDIT: hit comment by accident

    Since there is already a well-defined representation for these types in the first part of the journey, then why not reuse it for the second part? JSON-schema isn't really designed to validate non-JSON values, so the only opportunity to reuse a schema is where it's encoded.

  25. jviotti commented on Mar 7, 2018

    @jviotti

    What's the status of this? I have a use case for querying a RethinkDB table using JSON Schema, but this doesn't seem to be there yet.

  26. thelinuxlich commented on Mar 7, 2018

    @thelinuxlich

    After 2.4 is released with the write hooks feature, we can do a good validation, but not exactly JSON Schema syntax, at least not yet.

  27. srh commented on Mar 8, 2018

    @srh
    Contributor

    Yeah, nothing slick yet.

  28. jviotti commented on Mar 8, 2018

    @jviotti

    After 2.4 is released with the write hooks feature, we can do a good validation, but not exactly JSON Schema syntax, at least not yet.

    @thelinuxlich Would you point me to some docs? I'm struggling to find anything related to that.


    We're considering building a JSON Schema to ReQL translator to at least cover the essential JSON Schema keywords, but let me know if there is be a better way to get something like this up and running until this feature is properly implemented :)

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions