Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache storage #2076

Merged
merged 17 commits into from
Apr 20, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions lib/cache/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,12 @@ const assert = require('assert')
* @typedef {[any, any][]} requestResponseList
*/

class Cache {
/**
* The name of the cache
* @type {string}
*/
#id
/**
* @type {(o: Cache) => requestResponseList}
*/
let getCacheRequestResponseList
KhafraDev marked this conversation as resolved.
Show resolved Hide resolved

class Cache {
/**
* @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
* @type {requestResponseList}
Expand All @@ -43,7 +42,7 @@ class Cache {
webidl.illegalConstructor()
}

this.#id = arguments[1]
this.#relevantRequestResponseList = arguments[1]
}

async match (request, options = {}) {
Expand Down Expand Up @@ -640,6 +639,10 @@ class Cache {

return true
}

static {
getCacheRequestResponseList = (o) => o.#relevantRequestResponseList
}
}

Object.defineProperties(Cache.prototype, {
Expand Down Expand Up @@ -681,5 +684,6 @@ webidl.converters['sequence<RequestInfo>'] = webidl.sequenceConverter(
)

module.exports = {
Cache
Cache,
getCacheRequestResponseList
}
109 changes: 68 additions & 41 deletions lib/cache/cachestorage.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
'use strict'

const { kConstruct } = require('./symbols')
const { Cache } = require('./cache')
const { tmpdir, toCacheName } = require('./util')
const { Cache, getCacheRequestResponseList } = require('./cache')
const { webidl } = require('../fetch/webidl')
const { kEnumerableProperty } = require('../core/util')
const {
promises: {
rmdir,
mkdir,
readdir,
writeFile,
readFile
},
existsSync
} = require('fs')
const { join } = require('path')
const assert = require('assert')

class CacheStorage {
/**
* @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
* @type {Map<string, import('./cache').requestResponseList}
*/
#caches = new Map()

constructor () {
if (arguments[0] !== kConstruct) {
webidl.illegalConstructor()
Expand All @@ -33,60 +26,94 @@ class CacheStorage {
options = webidl.converters.CacheQueryOptions(options)
}

/**
* @see https://w3c.github.io/ServiceWorker/#cache-storage-has
* @param {string} cacheName
* @returns {Promise<boolean>}
*/
async has (cacheName) {
webidl.brandCheck(this, CacheStorage)
webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })

cacheName = toCacheName(cacheName)
cacheName = webidl.converters.DOMString(cacheName)

return existsSync(join(tmpdir, cacheName))
// 2.1.1
// 2.2
return this.#caches.has(cacheName)
}

/**
* @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
* @param {string} cacheName
* @returns {Promise<Cache>}
*/
async open (cacheName) {
webidl.brandCheck(this, CacheStorage)
webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })

const hashedName = toCacheName(cacheName)
const path = join(tmpdir, hashedName)
cacheName = webidl.converters.DOMString(cacheName)

// 2.1
if (this.#caches.has(cacheName)) {
// await caches.open('v1') !== await caches.open('v1')

// 2.1.1
const cache = this.#caches.get(cacheName)
const list = getCacheRequestResponseList(cache)

if (!existsSync(path)) {
await mkdir(path)
await writeFile(
join(path, `${hashedName}.json`),
JSON.stringify({ cacheName })
)
// 2.1.1.1
return new Cache(kConstruct, list)
}

return new Cache(kConstruct, hashedName)
// 2.2
const cache = []

// 2.3
this.#caches.set(cacheName, cache)

// 2.4
return new Cache(kConstruct, cache)
}

/**
* @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
* @param {string} cacheName
* @returns {Promise<boolean>}
*/
async delete (cacheName) {
webidl.brandCheck(this, CacheStorage)
webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })

cacheName = toCacheName(cacheName)
cacheName = webidl.converters.DOMString(cacheName)

return await rmdir(join(tmpdir, cacheName))
.then(() => true)
.catch(() => false)
}
// 1.
// 2.
const cacheExists = this.#caches.has(cacheName)

async keys () {
webidl.brandCheck(this, CacheStorage)
// 2.1
if (!cacheExists) {
return false
}

const dirs = await readdir(tmpdir, { withFileTypes: true })
/** @type {Promise<string>[]} */
const promises = []
// 2.3.1
this.#caches.delete(cacheName)

for (const dir of dirs) {
assert(dir.isDirectory(), `${dir.name} is not a directory`)
// 2.3.2
return true
}

const jsonPath = join(tmpdir, dir.name, `${dir.name}.json`)
/**
* @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
* @returns {string[]}
*/
async keys () {
webidl.brandCheck(this, CacheStorage)

promises.push(readFile(jsonPath, 'utf-8').then(cache => JSON.parse(cache).cacheName))
}
// 2.1
const keys = this.#caches.keys()

return Promise.all(promises)
// 2.2
return [...keys]
}
}

Expand Down
12 changes: 0 additions & 12 deletions lib/cache/util.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,6 @@
'use strict'

const { tmpdir } = require('os')
const { join } = require('path')
const { webidl } = require('../fetch/webidl')
const { URLSerializer } = require('../fetch/dataURL')
const { createHash } = require('crypto')

function toCacheName (V) {
V = webidl.converters.DOMString(V)

return createHash('MD5').update(V).digest('hex')
}

/**
* @see https://url.spec.whatwg.org/#concept-url-equals
Expand All @@ -28,7 +18,5 @@ function urlEquals (A, B, excludeFragment = false) {
}

module.exports = {
tmpdir: join(tmpdir(), 'undici-cache-storage'),
toCacheName,
urlEquals
}
2 changes: 0 additions & 2 deletions test/wpt/start-cacheStorage.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { join } from 'path'
import { fileURLToPath } from 'url'
import { fork } from 'child_process'
import { on } from 'events'
import { CacheStorage } from '../../lib/cache/cachestorage.js'
import { kConstruct } from '../../lib/cache/symbols.js'

const serverPath = fileURLToPath(join(import.meta.url, '../server/server.mjs'))

Expand Down