or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cache-operations.mdconfiguration.mderror-handling.mdindex.md
tile.json

cache-operations.mddocs/

Cache Operations

Core cache functionality for saving and restoring files using GitHub's caching service with support for both legacy (v1) and new (v2) cache services.

Capabilities

Feature Detection

Check if the Actions cache service is available in the current environment.

/**
 * Check the presence of Actions cache service
 * @returns true if Actions cache service feature is available, otherwise false
 */
function isFeatureAvailable(): boolean;

This function checks for the presence of required environment variables:

  • For v2 service: ACTIONS_RESULTS_URL
  • For v1 service: ACTIONS_CACHE_URL

Usage Example:

import { isFeatureAvailable } from '@actions/cache';

if (isFeatureAvailable()) {
  console.log('Cache service is available');
  // Proceed with cache operations
} else {
  console.log('Cache service is not available, skipping cache operations');
}

Cache Restoration

Restore cached files from the cache service using primary key and optional restore keys for fallback matching.

/**
 * Restores cache from keys
 * @param paths - List of file paths to restore from the cache
 * @param primaryKey - Explicit key for restoring the cache. Lookup is done with prefix matching
 * @param restoreKeys - Optional ordered list of keys to use for restoring the cache if no cache hit occurred for primaryKey
 * @param options - Cache download options
 * @param enableCrossOsArchive - Optional boolean enabled to restore on windows any cache created on any platform
 * @returns Cache key for cache hit, otherwise undefined
 */
function restoreCache(
  paths: string[],
  primaryKey: string,
  restoreKeys?: string[],
  options?: DownloadOptions,
  enableCrossOsArchive?: boolean = false
): Promise<string | undefined>;

Key Features:

  • Prefix Matching: Primary key and restore keys support prefix matching for flexible cache lookups
  • Fallback Strategy: If primary key doesn't match, tries restore keys in order
  • Cross-OS Support: Enables restoring caches created on different operating systems
  • Lookup Only Mode: Can check for cache existence without downloading via options.lookupOnly

Usage Examples:

import { restoreCache } from '@actions/cache';

// Basic cache restore
const paths = ['node_modules'];
const primaryKey = 'npm-deps-abc123';
const cacheKey = await restoreCache(paths, primaryKey);

if (cacheKey) {
  console.log(`Cache restored: ${cacheKey}`);
} else {
  console.log('Cache miss');
}

// With restore keys for fallback
const restoreKeys = [
  'npm-deps-abc',  // Less specific fallback
  'npm-deps-',     // Even less specific
  'npm-'           // Most general fallback
];

const cacheKey = await restoreCache(paths, primaryKey, restoreKeys);

// Lookup only (check existence without downloading)
const lookupOptions = { lookupOnly: true };
const existingKey = await restoreCache(paths, primaryKey, restoreKeys, lookupOptions);

if (existingKey) {
  console.log(`Cache exists with key: ${existingKey}`);
  // Decide whether to download it later
}

// Cross-OS restore (restore Windows cache on Linux)
const cacheKey = await restoreCache(paths, primaryKey, restoreKeys, undefined, true);

Cache Saving

Save files to the cache service with a specified key for future restoration.

/**
 * Saves a list of files with the specified key
 * @param paths - List of file paths to be cached
 * @param key - Explicit key for restoring the cache
 * @param options - Cache upload options
 * @param enableCrossOsArchive - Optional boolean enabled to save cache on windows which could be restored on any platform
 * @returns Cache ID if the cache was saved successfully, throws error if save fails
 */
function saveCache(
  paths: string[],
  key: string,
  options?: UploadOptions,
  enableCrossOsArchive?: boolean = false
): Promise<number>;

Key Features:

  • Automatic Compression: Uses zstandard (preferred) or gzip compression
  • Size Validation: Enforces 10GB size limit per repository
  • Cross-OS Support: Enables saving caches that can be restored on different operating systems
  • Chunked Upload: Large caches are uploaded in chunks for reliability

Usage Examples:

import { saveCache } from '@actions/cache';

// Basic cache save
const paths = [
  'node_modules',
  'packages/*/node_modules'
];
const key = 'npm-deps-abc123';

try {
  const cacheId = await saveCache(paths, key);
  console.log(`Cache saved successfully with ID: ${cacheId}`);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Validation error:', error.message);
  } else if (error instanceof ReserveCacheError) {
    console.warn('Cache reservation failed:', error.message);
  } else {
    console.error('Cache save failed:', error.message);
  }
}

// With upload options
const uploadOptions = {
  uploadConcurrency: 8,
  uploadChunkSize: 64 * 1024 * 1024, // 64MB chunks
  useAzureSdk: true
};

const cacheId = await saveCache(paths, key, uploadOptions);

// Cross-OS save (save on Windows, restore on Linux)
const cacheId = await saveCache(paths, key, undefined, true);

Cache Key Strategies

Key Validation Rules

Cache keys must follow these validation rules:

  • Maximum length: 512 characters
  • Cannot contain commas
  • Up to 10 keys total (including primary key and restore keys)

Best Practices

Hierarchical Keys: Use hierarchical key structure for better cache hit rates:

// Most specific to least specific
const primaryKey = `npm-${platform}-${arch}-${hashFiles('package-lock.json')}`;
const restoreKeys = [
  `npm-${platform}-${arch}-`,
  `npm-${platform}-`,
  `npm-`
];

Content-Based Keys: Include file hashes in keys for cache invalidation:

import { createHash } from 'crypto';
import { readFileSync } from 'fs';

function hashFiles(pattern: string): string {
  // Implementation to hash files matching pattern
  const content = readFileSync('package-lock.json', 'utf8');
  return createHash('sha256').update(content).digest('hex');
}

const key = `deps-${hashFiles('**/package-lock.json')}`;

Error Handling

Cache operations can throw several types of errors:

ValidationError

Thrown for validation failures like invalid key format or missing paths:

try {
  await restoreCache([], 'key'); // Empty paths
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Validation failed:', error.message);
    // Handle validation error
  }
}

ReserveCacheError

Thrown when unable to reserve cache, typically when another job is creating the same cache:

try {
  await saveCache(paths, key);
} catch (error) {
  if (error instanceof ReserveCacheError) {
    console.warn('Cache reservation failed:', error.message);
    // Another job may be creating this cache, continue without caching
  }
}

General Errors

Other errors are logged as warnings and don't break the workflow:

try {
  const cacheKey = await restoreCache(paths, primaryKey, restoreKeys);
} catch (error) {
  // Cache failures are non-blocking - workflow continues
  console.warn('Cache operation failed:', error.message);
}