summaryrefslogtreecommitdiff
path: root/cli/cache/code_cache.rs
blob: abcd0d46ac1cfffe9faad8dec3a94b6825c7ab39 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

use deno_ast::ModuleSpecifier;
use deno_core::error::AnyError;
use deno_runtime::code_cache;
use deno_runtime::deno_webstorage::rusqlite::params;

use super::cache_db::CacheDB;
use super::cache_db::CacheDBConfiguration;
use super::cache_db::CacheDBHash;
use super::cache_db::CacheFailure;

pub static CODE_CACHE_DB: CacheDBConfiguration = CacheDBConfiguration {
  table_initializer: concat!(
    "CREATE TABLE IF NOT EXISTS codecache (",
    "specifier TEXT NOT NULL,",
    "type INTEGER NOT NULL,",
    "source_hash INTEGER NOT NULL,",
    "data BLOB NOT NULL,",
    "PRIMARY KEY (specifier, type)",
    ");"
  ),
  on_version_change: "DELETE FROM codecache;",
  preheat_queries: &[],
  on_failure: CacheFailure::Blackhole,
};

pub struct CodeCache {
  inner: CodeCacheInner,
}

impl CodeCache {
  pub fn new(db: CacheDB) -> Self {
    Self {
      inner: CodeCacheInner::new(db),
    }
  }

  fn ensure_ok<T: Default>(res: Result<T, AnyError>) -> T {
    match res {
      Ok(x) => x,
      Err(err) => {
        // TODO(mmastrac): This behavior was inherited from before the refactoring but it probably makes sense to move it into the cache
        // at some point.
        // should never error here, but if it ever does don't fail
        if cfg!(debug_assertions) {
          panic!("Error using code cache: {err:#}");
        } else {
          log::debug!("Error using code cache: {:#}", err);
        }
        T::default()
      }
    }
  }

  pub fn get_sync(
    &self,
    specifier: &ModuleSpecifier,
    code_cache_type: code_cache::CodeCacheType,
    source_hash: u64,
  ) -> Option<Vec<u8>> {
    Self::ensure_ok(self.inner.get_sync(
      specifier.as_str(),
      code_cache_type,
      CacheDBHash::new(source_hash),
    ))
  }

  pub fn set_sync(
    &self,
    specifier: &ModuleSpecifier,
    code_cache_type: code_cache::CodeCacheType,
    source_hash: u64,
    data: &[u8],
  ) {
    Self::ensure_ok(self.inner.set_sync(
      specifier.as_str(),
      code_cache_type,
      CacheDBHash::new(source_hash),
      data,
    ));
  }
}

impl code_cache::CodeCache for CodeCache {
  fn get_sync(
    &self,
    specifier: &ModuleSpecifier,
    code_cache_type: code_cache::CodeCacheType,
    source_hash: u64,
  ) -> Option<Vec<u8>> {
    self.get_sync(specifier, code_cache_type, source_hash)
  }

  fn set_sync(
    &self,
    specifier: ModuleSpecifier,
    code_cache_type: code_cache::CodeCacheType,
    source_hash: u64,
    data: &[u8],
  ) {
    self.set_sync(&specifier, code_cache_type, source_hash, data);
  }
}

struct CodeCacheInner {
  conn: CacheDB,
}

impl CodeCacheInner {
  pub fn new(conn: CacheDB) -> Self {
    Self { conn }
  }

  pub fn get_sync(
    &self,
    specifier: &str,
    code_cache_type: code_cache::CodeCacheType,
    source_hash: CacheDBHash,
  ) -> Result<Option<Vec<u8>>, AnyError> {
    let query = "
      SELECT
        data
      FROM
        codecache
      WHERE
        specifier=?1 AND type=?2 AND source_hash=?3
      LIMIT 1";
    let params = params![
      specifier,
      serialize_code_cache_type(code_cache_type),
      source_hash,
    ];
    self.conn.query_row(query, params, |row| {
      let value: Vec<u8> = row.get(0)?;
      Ok(value)
    })
  }

  pub fn set_sync(
    &self,
    specifier: &str,
    code_cache_type: code_cache::CodeCacheType,
    source_hash: CacheDBHash,
    data: &[u8],
  ) -> Result<(), AnyError> {
    let sql = "
      INSERT OR REPLACE INTO
        codecache (specifier, type, source_hash, data)
      VALUES
        (?1, ?2, ?3, ?4)";
    let params = params![
      specifier,
      serialize_code_cache_type(code_cache_type),
      source_hash,
      data
    ];
    self.conn.execute(sql, params)?;
    Ok(())
  }
}

fn serialize_code_cache_type(
  code_cache_type: code_cache::CodeCacheType,
) -> i64 {
  match code_cache_type {
    code_cache::CodeCacheType::Script => 0,
    code_cache::CodeCacheType::EsModule => 1,
  }
}

#[cfg(test)]
mod test {
  use super::*;

  #[test]
  pub fn end_to_end() {
    let conn = CacheDB::in_memory(&CODE_CACHE_DB, "1.0.0");
    let cache = CodeCacheInner::new(conn);

    assert!(cache
      .get_sync(
        "file:///foo/bar.js",
        code_cache::CodeCacheType::EsModule,
        CacheDBHash::new(1),
      )
      .unwrap()
      .is_none());
    let data_esm = vec![1, 2, 3];
    cache
      .set_sync(
        "file:///foo/bar.js",
        code_cache::CodeCacheType::EsModule,
        CacheDBHash::new(1),
        &data_esm,
      )
      .unwrap();
    assert_eq!(
      cache
        .get_sync(
          "file:///foo/bar.js",
          code_cache::CodeCacheType::EsModule,
          CacheDBHash::new(1),
        )
        .unwrap()
        .unwrap(),
      data_esm
    );

    assert!(cache
      .get_sync(
        "file:///foo/bar.js",
        code_cache::CodeCacheType::Script,
        CacheDBHash::new(1),
      )
      .unwrap()
      .is_none());
    let data_script = vec![4, 5, 6];
    cache
      .set_sync(
        "file:///foo/bar.js",
        code_cache::CodeCacheType::Script,
        CacheDBHash::new(1),
        &data_script,
      )
      .unwrap();
    assert_eq!(
      cache
        .get_sync(
          "file:///foo/bar.js",
          code_cache::CodeCacheType::Script,
          CacheDBHash::new(1),
        )
        .unwrap()
        .unwrap(),
      data_script
    );
    assert_eq!(
      cache
        .get_sync(
          "file:///foo/bar.js",
          code_cache::CodeCacheType::EsModule,
          CacheDBHash::new(1),
        )
        .unwrap()
        .unwrap(),
      data_esm
    );
  }
}