Skip to content

Add ability to remove keys by type or API call #85

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

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
51 changes: 51 additions & 0 deletions docs/content/1.getting-started/1.index.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,38 @@ The port the server should listen on.

The directory to use for temporary files.

#### `ENABLE_TYPED_KEY_PREFIX_REMOVAL`

- Default: `false`

If enabled then any specifically structured keys will be automatically removed if there are more keys of such type than
the amount specified via `MAX_STORED_KEYS_PER_TYPE`.
Key type is defined by the following format:
`{key_type}{TYPED_KEY_DELIMITER}{optional custom string}`
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the purpose of the optional custom string?


Usually, it's recommended to use the following key structure:
`{repository_name}_{branch}_{unique_key_name}{TYPED_KEY_DELIMITER}{hash or other unique data}`

An example could look like:
`falcondev-oss/github-actions-cache-server_dev_docker-cache@#@16ee33c5f9f59c0`

In such case older keys with prefix `falcondev-oss/github-actions-cache-server_dev_docker-cache` will be automatically
removed whenever there are more records for this key type then the one specified via `MAX_STORED_KEYS_PER_TYPE`.

#### `MAX_STORED_KEYS_PER_TYPE`

- Default: `3`

If `ENABLE_TYPED_KEY_PREFIX_REMOVAL` is `true` then this is the maximum amount of the most recent keys to keep per key type.
Any other older keys will be automatically removed.

#### `TYPED_KEY_DELIMITER`
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe cache keys cannot contain , so we could just use it as a delimiter


- Default: `@#@`

If `ENABLE_TYPED_KEY_PREFIX_REMOVAL` is `true` then this is the delimiter which is used to identify the key type.
Any prefix before `@#@` is considered to be the key type.

## 2. Setup with Self-Hosted Runners

Set the `ACTIONS_RESULTS_URL` on your runner to the API URL (with a trailing slash).
Expand Down Expand Up @@ -148,3 +180,22 @@ variant: subtle
There is no need to change any of your workflows! 🔥

If you've set up your self-hosted runners correctly, they will automatically use the cache server for caching.

## 4. Cache cleanup

Cache cleanup can be triggered automatically via configured eviction policies like:
- `CLEANUP_OLDER_THAN_DAYS` - eviction by time.
- `ENABLE_TYPED_KEY_PREFIX_REMOVAL` - eviction by key type (key prefix).

Moreover, an additional API exists which can be used to evict key records by using specified key prefix.
API path: `/extra/clear_key_prefix`. API method: `POST`.
Request body: `{ keyPrefix: string }`.

Any keys with the prefix of `keyPrefix` will be removed and data will be cleared for such keys.
Usually, it's useful to call keys removal for an archived branch or a closed PR where you know that the cache won't
be reused anymore. For such cases you could have a step which is called and clears all keys prefixed with the branch name.
For example:
```
- name: Remove keys by prefix
run: curl --header "Content-Type: application/json" --request POST --data '{"keyPrefix":"${{ github.head_ref || github.ref_name }}"}' "${ACTIONS_RESULTS_URL}extra/clear_key_prefix"
```
25 changes: 25 additions & 0 deletions lib/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,31 @@ export async function findStaleKeys(
.execute()
}

export async function findPrefixedKeysForRemoval(
db: DB,
{ keyPrefix, skipRecentKeysLimit }: { keyPrefix: string; skipRecentKeysLimit?: number; },
) {

let query = db
.selectFrom('cache_keys')
.where('key', 'like', `${keyPrefix}%`)

if (skipRecentKeysLimit && skipRecentKeysLimit > 0){
query = query.where(({ eb, selectFrom, not }) => not(eb(
'id',
'in',
selectFrom('cache_keys')
.select('cache_keys.id')
.orderBy('cache_keys.accessed_at desc')
.limit(skipRecentKeysLimit)
)))
}

return query
.selectAll()
.execute()
}

export async function createKey(
db: DB,
{ key, version, date }: { key: string; version: string; date?: Date },
Expand Down
3 changes: 3 additions & 0 deletions lib/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ const envSchema = z.object({
DEBUG: booleanSchema.default('false'),
NITRO_PORT: portSchema.default(3000),
TEMP_DIR: z.string().default(tmpdir()),
ENABLE_TYPED_KEY_PREFIX_REMOVAL: booleanSchema.default('false'),
MAX_STORED_KEYS_PER_TYPE: z.coerce.number().int().min(0).default(3),
TYPED_KEY_DELIMITER: z.string().default('@#@'),
})

const parsedEnv = envSchema.safeParse(process.env)
Expand Down
43 changes: 41 additions & 2 deletions lib/storage/index.ts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of adding more functions for the different methods of pruning caches, I would just add filter functionality to the existing pruneCaches function. This file now also has many untyped functions which should be avoided.

Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
touchKey,
updateOrCreateKey,
useDB,
findPrefixedKeysForRemoval,

Check failure on line 16 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 💅 Lint

Expected "findPrefixedKeysForRemoval" to come before "useDB"
} from '~/lib/db'
import { ENV } from '~/lib/env'
import { logger } from '~/lib/logger'
Expand All @@ -21,6 +22,7 @@
import { getObjectNameFromKey } from '~/lib/utils'

export interface Storage {
pruneCacheByKeyPrefix: (keyPrefix: string) => Promise<void>
getCacheEntry: (
keys: string[],
version: string,
Expand Down Expand Up @@ -68,9 +70,44 @@
const driver = await driverSetup()
const db = await useDB()

storage = {
storage = {

async pruneCacheKeys(keysForRemoval){

Check failure on line 75 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 🛃 Type Check

Parameter 'keysForRemoval' implicitly has an 'any' type.

Check failure on line 75 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 🛃 Type Check

Object literal may only specify known properties, but 'pruneCacheKeys' does not exist in type 'Storage'. Did you mean to write 'pruneCaches'?
if (keysForRemoval.length === 0) {
logger.debug('Prune: No caches to prune')
return
}

await driver.delete({
objectNames: keysForRemoval.map((key) => getObjectNameFromKey(key.key, key.version)),

Check failure on line 82 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 🛃 Type Check

Parameter 'key' implicitly has an 'any' type.
})

await pruneKeys(db, keysForRemoval)
},

async pruneStaleCacheByType(key){

Check failure on line 88 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 🛃 Type Check

Parameter 'key' implicitly has an 'any' type.
if (!ENV.ENABLE_TYPED_KEY_PREFIX_REMOVAL){
return
}
let keyTypeIndex = key.indexOf(ENV.TYPED_KEY_DELIMITER)

Check failure on line 92 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 💅 Lint

'keyTypeIndex' is never reassigned. Use 'const' instead
if (keyTypeIndex < 1){
return
}
let keyType = key.substring(0, keyTypeIndex)

Check failure on line 96 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 💅 Lint

Prefer `String#slice()` over `String#substring()`

Check failure on line 96 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 💅 Lint

'keyType' is never reassigned. Use 'const' instead
logger.debug(`Prune by type is called: Type [${keyType}]. Full key [${key}].`)
let keysForRemoval = await findPrefixedKeysForRemoval(db, { keyPrefix: keyType, skipRecentKeysLimit: ENV.MAX_STORED_KEYS_PER_TYPE } )

Check failure on line 98 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 💅 Lint

'keysForRemoval' is never reassigned. Use 'const' instead
logger.debug(`Removing ${keysForRemoval.length} keys for prefix [${keyType}].`)
await this.pruneCacheKeys(keysForRemoval)

Check failure on line 100 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 🛃 Type Check

Property 'pruneCacheKeys' does not exist on type 'Storage'. Did you mean 'pruneCaches'?
},

async pruneCacheByKeyPrefix(keyPrefix){
let keysForRemoval = await findPrefixedKeysForRemoval(db, { keyPrefix: keyPrefix, skipRecentKeysLimit: 0 } )

Check failure on line 104 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 💅 Lint

Expected property shorthand

Check failure on line 104 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 💅 Lint

'keysForRemoval' is never reassigned. Use 'const' instead
logger.debug(`Removing ${keysForRemoval.length} keys for prefix [${keyPrefix}].`)
await this.pruneCacheKeys(keysForRemoval)

Check failure on line 106 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 🛃 Type Check

Property 'pruneCacheKeys' does not exist on type 'Storage'. Did you mean 'pruneCaches'?
},

async reserveCache(key, version, totalSize) {
logger.debug('Reserve:', { key, version })
logger.debug('Reserve:', { key, version })

if (await getUpload(db, { key, version })) {
logger.debug(`Reserve: Already reserved. Ignoring...`, { key, version })
Expand Down Expand Up @@ -103,6 +140,8 @@
uploadId,
})

this.pruneStaleCacheByType(key)

Check failure on line 143 in lib/storage/index.ts

View workflow job for this annotation

GitHub Actions / 🛃 Type Check

Property 'pruneStaleCacheByType' does not exist on type 'Storage'.

return {
cacheId: uploadId,
}
Expand Down
26 changes: 26 additions & 0 deletions routes/extra/clear_key_prefix.post.ts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably take the same params as the GET _apis/artifactcache/cache route:

  • keys
  • optional version

I would also prefer a route name like /extra/caches/prune

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { z } from 'zod'

import { useStorageAdapter } from '~/lib/storage'

const bodySchema = z.object({
keyPrefix: z.string().min(1),
})

export default defineEventHandler(async (event) => {
const body = (await readBody(event)) as unknown
const parsedBody = bodySchema.safeParse(body)
if (!parsedBody.success)
throw createError({
statusCode: 400,
statusMessage: `Invalid body: ${parsedBody.error.message}`,
})

const { keyPrefix } = parsedBody.data

const adapter = await useStorageAdapter()
adapter.pruneCacheByKeyPrefix(keyPrefix)

return {
ok: true,
}
})
Loading