Repository navigation
Description
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
danielmewes commentedon Mar 9, 2016
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.
danielmewes commentedon Mar 9, 2016
I'm going to put this into
subsequentfor 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 .
thelinuxlich commentedon Mar 11, 2016
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.mbroadst commentedon Jul 5, 2016
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?
mbroadst commentedon Jul 6, 2016
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_configif you did something liker.table('mytable').schema({ some: { json: 'schema' } })? I've already worked out the json-schema for custom reql types (all the geo types, dates, etc) inthinkagain, so those could be baked in and leveraged.danielmewes commentedon Jul 7, 2016
@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) -> boolcommand. 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.
marshall007 commentedon Jul 7, 2016
@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?
danielmewes commentedon Jul 7, 2016
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.
mbroadst commentedon Jul 7, 2016
@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?
mbroadst commentedon Jul 12, 2016
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.schemapseudo-type, as well as ar.validateoperation (which operates on datum). This looks like: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_trather than a need to convert to and from rapidjson'sValuetype.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
thinkagainalready 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 asr.schema().validate(datum)mbroadst commentedon Sep 2, 2016
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? 😄
10 remaining items
marshall007 commentedon Sep 8, 2016
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.rowandbracketterms (ignoring their context) with fields in the schema for the table in the current query would go a long way.segphault commentedon Sep 9, 2016
I'm pretty excited to see this moving forward. 👍
chrisvariety commentedon Sep 9, 2016
@segphault FYI
additionalPropertiesis built into JSON-schema and does... exactly what you would expect, so I think that base is covered!marshall007 commentedon Sep 9, 2016
@segphault the problem with using
$reffor pseudotypes is that it will bomb on json-schema clients that don't support overloading the behavior of that attribute. On the other hand,formatis supposed to be ignored when the client doesn't support the attribute and/or keyword. Per spec:formatdefinitely offers the most flexibility for users in defining their schema and portability across client implementations.segphault commentedon Sep 9, 2016
@chrisvariety yep, I'm aware of
additionalProperties. The suggestion that I was making has to do with how it's handled. WhenadditionalPropertiesis 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.
mike-marcacci commentedon Sep 9, 2016
@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
formatis 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.
mbroadst commentedon Sep 9, 2016
useDefaults(fills in default values => maps todefaultreql term),removeAdditional(remove properties not defined in the schema, I think this satisfies @segphault 's request above?), etc.r.schemavsr.model, signals intent better.formatis definitely the best option for informing the RethinkDB side of the validation equation. As @marshall007 pointed out earlier, ajv does not presently supportformaton 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 regardformatcould 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.format, e.g.reql_type: 'date'. This could lead to some flexibility considering that theanytype 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.typevalues is an absolute non-starter, as it will break spec.$refshould indeed be used for pseudo-types (we can rip them right fromthinkagaintbh), however I believeformat(orreql_type?) should still be used for additional contextual type information. Figuring out how the user wants to send/receive aDateis 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 thinkformatcan help here given it's flexibility.marshall007 commentedon Sep 9, 2016
@mike-marcacci yea so the issue is that for
date,binary, andgeotypes, 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,
$refdoes 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, strictContent-Securitypolicies, 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.marshall007 commentedon Sep 9, 2016
@segphault so to clarify, even if your client was able to seamlessly integrate the
$refschema, that's not even necessarily what you want to be validating against in a given context.segphault commentedon Sep 9, 2016
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.
mike-marcacci commentedon Sep 9, 2016
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
formatto 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.
jviotti commentedon Mar 7, 2018
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.
thelinuxlich commentedon Mar 7, 2018
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.
srh commentedon Mar 8, 2018
Yeah, nothing slick yet.
jviotti commentedon Mar 8, 2018
@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 :)