File
Blob: src/workerd/jsg/compile-cache.h
| 1 | // Copyright (c) 2017-2022 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | #pragma once |
| 5 | |
| 6 | #include <v8-script.h> |
| 7 | |
| 8 | #include <kj/map.h> |
| 9 | #include <kj/mutex.h> |
| 10 | #include <kj/string.h> |
| 11 | |
| 12 | namespace workerd::jsg { |
| 13 | |
| 14 | // The CompileCache is used to hold cached compilation data for built-in JavaScript modules. |
| 15 | // |
| 16 | // Importantly, this is a process-lifetime in-memory cache that is only appropriate for |
| 17 | // built-in modules. |
| 18 | // |
| 19 | // The memory-safety of this cache depends on the assumption that entries are never removed |
| 20 | // or replaced. If things are ever changed such that entries are removed/replaced, then |
| 21 | // we'd likely need to have find return an atomic refcount or something similar. |
| 22 | class CompileCache { |
| 23 | public: |
| 24 | class Data { |
| 25 | public: |
| 26 | Data(): data(nullptr), length(0), owningPtr(nullptr) {}; |
| 27 | explicit Data(std::shared_ptr<v8::ScriptCompiler::CachedData> cached_data) |
| 28 | : data(cached_data->data), |
| 29 | length(cached_data->length), |
| 30 | owningPtr(cached_data) {}; |
| 31 | |
| 32 | // Returns a v8::ScriptCompiler::CachedData corresponding to this |
| 33 | // CompileCache::Data. The lifetime of the returned |
| 34 | // v8::ScriptCompiler::CachedData must not outlive that of the data. |
| 35 | std::unique_ptr<v8::ScriptCompiler::CachedData> AsCachedData(); |
| 36 | |
| 37 | const uint8_t* data; |
| 38 | size_t length; |
| 39 | |
| 40 | private: |
| 41 | std::shared_ptr<void> owningPtr; |
| 42 | }; |
| 43 | |
| 44 | void add(kj::StringPtr key, std::shared_ptr<v8::ScriptCompiler::CachedData> cached) const; |
| 45 | kj::Maybe<Data&> find(kj::StringPtr key) const; |
| 46 | |
| 47 | static const CompileCache& get() { |
| 48 | static const CompileCache instance; |
| 49 | return instance; |
| 50 | } |
| 51 | |
| 52 | private: |
| 53 | // The key is the address of the static global that was compiled to produce the CachedData. |
| 54 | kj::MutexGuarded<kj::HashMap<kj::String, Data>> cache; |
| 55 | }; |
| 56 | |
| 57 | } // namespace workerd::jsg |