Skip to content

Commit

Permalink
feat: http perma cache status get (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
vasco-santos authored May 11, 2022
1 parent df3318e commit 271bd85
Show file tree
Hide file tree
Showing 4 changed files with 113 additions and 1 deletion.
6 changes: 5 additions & 1 deletion packages/api/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
withApiToken,
withSuperHotAuthorized,
} from './auth.js'
import { permaCachePost, permaCacheListGet } from './perma-cache/index.js'
import { permaCachePost, permaCacheListGet, permaCacheStatusGet } from './perma-cache/index.js'

import { addCorsHeaders, withCorsHeaders } from './cors.js'
import { errorHandler } from './error-handler.js'
Expand All @@ -30,6 +30,10 @@ router
})
.get('/perma-cache', auth['🔒'](auth['🚫'](auth['🔥'](permaCacheListGet))))
.post('/perma-cache/:url', auth['🔒'](auth['🚫'](auth['🔥'](permaCachePost))))
.get(
'/perma-cache/status',
auth['🔒'](auth['🚫'](auth['🔥'](permaCacheStatusGet)))
)

/**
* @param {Error} error
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/perma-cache/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { permaCachePost } from './post.js'
export { permaCacheListGet } from './get.js'
export { permaCacheStatusGet } from './status.js'
52 changes: 52 additions & 0 deletions packages/api/src/perma-cache/status.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/* eslint-env serviceworker, browser */
/* global Response */
import { HTTPError } from '../errors.js'
import { JSONResponse } from '../utils/json-response.js'

/**
* @typedef {import('../env').Env} Env
*/

/**
* Handle perma-cache status get request
*
* @param {Request} request
* @param {Env} env
*/
export async function permaCacheStatusGet(request, env) {
const kvPrefix = `${request.auth.user.id}`
let usedStorage = 0
let endCursor

// Iterate KV user prefix and get all the content
do {
const {
keys,
cursor,
list_complete: listComplete,
} = await env.PERMACACHE.list({
prefix: kvPrefix,
limit: 1000,
cursor: endCursor,
})

if (!keys) {
throw new HTTPError('No perma cached content found for given user')
}

keys.forEach((key) => {
usedStorage += key.metadata.contentLength
})

endCursor = cursor

// Stop looking if no other entries available
if (listComplete) {
endCursor = undefined
}
} while (endCursor)

return new JSONResponse({
usedStorage,
})
}
55 changes: 55 additions & 0 deletions packages/api/test/perma-cache-status.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import test from 'ava'

import { getMiniflare } from './scripts/utils.js'
import { createTestUser } from './scripts/helpers.js'

test.beforeEach(async (t) => {
const user = await createTestUser({
grantRequiredTags: true,
})

// Create a new Miniflare environment for each test
t.context = {
mf: getMiniflare(),
user,
}
})

test('Get perma cache status from user', async (t) => {
const { mf, user } = t.context
const statusResponseEmpty = await mf.dispatchFetch(
'https://localhost:8788/perma-cache/status',
{
method: 'GET',
headers: { Authorization: `Bearer ${user.token}` },
}
)
t.is(statusResponseEmpty.status, 200)

const statusEmpty = await statusResponseEmpty.json()
t.is(statusEmpty.usedStorage, 0)

const url =
'http://bafkreidyeivj7adnnac6ljvzj2e3rd5xdw3revw4da7mx2ckrstapoupoq.ipfs.localhost:9081'
const response = await mf.dispatchFetch(getPermaCachePutUrl(url), {
method: 'POST',
headers: { Authorization: `Bearer ${user.token}` },
})
t.is(response.status, 200)
const body = await response.json()

const statusResponseNotEmpty = await mf.dispatchFetch(
'https://localhost:8788/perma-cache/status',
{
method: 'GET',
headers: { Authorization: `Bearer ${user.token}` },
}
)
t.is(statusResponseNotEmpty.status, 200)

const statusNotEmpty = await statusResponseNotEmpty.json()
t.is(statusNotEmpty.usedStorage, body.contentLength)
})

const getPermaCachePutUrl = (url) =>
`https://localhost:8788/perma-cache/${encodeURIComponent(url)}`

0 comments on commit 271bd85

Please sign in to comment.