capnproto

FORK: Cap'n Proto serialization/RPC system - core tools and C++ library
git clone https://git.neptards.moe/neptards/capnproto.git
Log | Files | Refs | README | LICENSE

schema-loader.h (8544B)


      1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
      2 // Licensed under the MIT License:
      3 //
      4 // Permission is hereby granted, free of charge, to any person obtaining a copy
      5 // of this software and associated documentation files (the "Software"), to deal
      6 // in the Software without restriction, including without limitation the rights
      7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      8 // copies of the Software, and to permit persons to whom the Software is
      9 // furnished to do so, subject to the following conditions:
     10 //
     11 // The above copyright notice and this permission notice shall be included in
     12 // all copies or substantial portions of the Software.
     13 //
     14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     20 // THE SOFTWARE.
     21 
     22 #pragma once
     23 
     24 #include "schema.h"
     25 #include <kj/memory.h>
     26 #include <kj/mutex.h>
     27 
     28 CAPNP_BEGIN_HEADER
     29 
     30 namespace capnp {
     31 
     32 class SchemaLoader {
     33   // Class which can be used to construct Schema objects from schema::Nodes as defined in
     34   // schema.capnp.
     35   //
     36   // It is a bad idea to use this class on untrusted input with exceptions disabled -- you may
     37   // be exposing yourself to denial-of-service attacks, as attackers can easily construct schemas
     38   // that are subtly inconsistent in a way that causes exceptions to be thrown either by
     39   // SchemaLoader or by the dynamic API when the schemas are subsequently used.  If you enable and
     40   // properly catch exceptions, you should be OK -- assuming no bugs in the Cap'n Proto
     41   // implementation, of course.
     42 
     43 public:
     44   class LazyLoadCallback {
     45   public:
     46     virtual void load(const SchemaLoader& loader, uint64_t id) const = 0;
     47     // Request that the schema node with the given ID be loaded into the given SchemaLoader.  If
     48     // the callback is able to find a schema for this ID, it should invoke `loadOnce()` on
     49     // `loader` to load it.  If no such node exists, it should simply do nothing and return.
     50     //
     51     // The callback is allowed to load schema nodes other than the one requested, e.g. because it
     52     // expects they will be needed soon.
     53     //
     54     // If the `SchemaLoader` is used from multiple threads, the callback must be thread-safe.
     55     // In particular, it's possible for multiple threads to invoke `load()` with the same ID.
     56     // If the callback performs a large amount of work to look up IDs, it should be sure to
     57     // de-dup these requests.
     58   };
     59 
     60   SchemaLoader();
     61 
     62   SchemaLoader(const LazyLoadCallback& callback);
     63   // Construct a SchemaLoader which will invoke the given callback when a schema node is requested
     64   // that isn't already loaded.
     65 
     66   ~SchemaLoader() noexcept(false);
     67   KJ_DISALLOW_COPY(SchemaLoader);
     68 
     69   Schema get(uint64_t id, schema::Brand::Reader brand = schema::Brand::Reader(),
     70              Schema scope = Schema()) const;
     71   // Gets the schema for the given ID, throwing an exception if it isn't present.
     72   //
     73   // The returned schema may be invalidated if load() is called with a new schema for the same ID.
     74   // In general, you should not call load() while a schema from this loader is in-use.
     75   //
     76   // `brand` and `scope` are used to determine brand bindings where relevant. `brand` gives
     77   // parameter bindings for the target type's brand parameters that were specified at the reference
     78   // site. `scope` specifies the scope in which the type ID appeared -- if `brand` itself contains
     79   // parameter references or indicates that some parameters will be inherited, these will be
     80   // interpreted within / inherited from `scope`.
     81 
     82   kj::Maybe<Schema> tryGet(uint64_t id, schema::Brand::Reader bindings = schema::Brand::Reader(),
     83                            Schema scope = Schema()) const;
     84   // Like get() but doesn't throw.
     85 
     86   Schema getUnbound(uint64_t id) const;
     87   // Gets a special version of the schema in which all brand parameters are "unbound". This means
     88   // that if you look up a type via the Schema API, and it resolves to a brand parameter, the
     89   // returned Type's getBrandParameter() method will return info about that parameter. Otherwise,
     90   // normally, all brand parameters that aren't otherwise bound are assumed to simply be
     91   // "AnyPointer".
     92 
     93   Type getType(schema::Type::Reader type, Schema scope = Schema()) const;
     94   // Convenience method which interprets a schema::Type to produce a Type object. Implemented in
     95   // terms of get().
     96 
     97   Schema load(const schema::Node::Reader& reader);
     98   // Loads the given schema node.  Validates the node and throws an exception if invalid.  This
     99   // makes a copy of the schema, so the object passed in can be destroyed after this returns.
    100   //
    101   // If the node has any dependencies which are not already loaded, they will be initialized as
    102   // stubs -- empty schemas of whichever kind is expected.
    103   //
    104   // If another schema for the given reader has already been seen, the loader will inspect both
    105   // schemas to determine which one is newer, and use that that one.  If the two versions are
    106   // found to be incompatible, an exception is thrown.  If the two versions differ but are
    107   // compatible and the loader cannot determine which is newer (e.g., the only changes are renames),
    108   // the existing schema will be preferred.  Note that in any case, the loader will end up keeping
    109   // around copies of both schemas, so you shouldn't repeatedly reload schemas into the same loader.
    110   //
    111   // The following properties of the schema node are validated:
    112   // - Struct size and preferred list encoding are valid and consistent.
    113   // - Struct members are fields or unions.
    114   // - Union members are fields.
    115   // - Field offsets are in-bounds.
    116   // - Ordinals and codeOrders are sequential starting from zero.
    117   // - Values are of the right union case to match their types.
    118   //
    119   // You should assume anything not listed above is NOT validated.  In particular, things that are
    120   // not validated now, but could be in the future, include but are not limited to:
    121   // - Names.
    122   // - Annotation values.  (This is hard because the annotation declaration is not always
    123   //   available.)
    124   // - Content of default/constant values of pointer type.  (Validating these would require knowing
    125   //   their schema, but even if the schemas are available at validation time, they could be
    126   //   updated by a subsequent load(), invalidating existing values.  Instead, these values are
    127   //   validated at the time they are used, as usual for Cap'n Proto objects.)
    128   //
    129   // Also note that unknown types are not considered invalid.  Instead, the dynamic API returns
    130   // a DynamicValue with type UNKNOWN for these.
    131 
    132   Schema loadOnce(const schema::Node::Reader& reader) const;
    133   // Like `load()` but does nothing if a schema with the same ID is already loaded.  In contrast,
    134   // `load()` would attempt to compare the schemas and take the newer one.  `loadOnce()` is safe
    135   // to call even while concurrently using schemas from this loader.  It should be considered an
    136   // error to call `loadOnce()` with two non-identical schemas that share the same ID, although
    137   // this error may or may not actually be detected by the implementation.
    138 
    139   template <typename T>
    140   void loadCompiledTypeAndDependencies();
    141   // Load the schema for the given compiled-in type and all of its dependencies.
    142   //
    143   // If you want to be able to cast a DynamicValue built from this SchemaLoader to the compiled-in
    144   // type using as<T>(), you must call this method before constructing the DynamicValue.  Otherwise,
    145   // as<T>() will throw an exception complaining about type mismatch.
    146 
    147   kj::Array<Schema> getAllLoaded() const;
    148   // Get a complete list of all loaded schema nodes.  It is particularly useful to call this after
    149   // loadCompiledTypeAndDependencies<T>() in order to get a flat list of all of T's transitive
    150   // dependencies.
    151 
    152 private:
    153   class Validator;
    154   class CompatibilityChecker;
    155   class Impl;
    156   class InitializerImpl;
    157   class BrandedInitializerImpl;
    158   kj::MutexGuarded<kj::Own<Impl>> impl;
    159 
    160   void loadNative(const _::RawSchema* nativeSchema);
    161 };
    162 
    163 template <typename T>
    164 inline void SchemaLoader::loadCompiledTypeAndDependencies() {
    165   loadNative(&_::rawSchema<T>());
    166 }
    167 
    168 }  // namespace capnp
    169 
    170 CAPNP_END_HEADER