CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-openrewrite--rewrite-maven

OpenRewrite Maven parsing and refactoring library that provides Maven POM file parsing, analysis, and automated refactoring capabilities

Pending
Overview
Eval results
Files

caching.mddocs/

Caching System

Pluggable caching interfaces and implementations for Maven artifacts and POM files to improve performance.

Capabilities

Core Caching Interfaces

MavenArtifactCache

Interface for caching Maven artifacts with get/put operations.

/**
 * Interface for caching Maven artifacts to improve performance
 */
public interface MavenArtifactCache {
    /**
     * Get cached artifact content
     * @param gav Group:Artifact:Version coordinate
     * @return Cached artifact bytes or null if not cached
     */
    @Nullable byte[] get(GroupArtifactVersion gav);
    
    /**
     * Cache artifact content
     * @param gav Group:Artifact:Version coordinate  
     * @param artifact Artifact bytes to cache
     */
    void put(GroupArtifactVersion gav, byte[] artifact);
    
    /**
     * Check if artifact is cached
     * @param gav Group:Artifact:Version coordinate
     * @return true if artifact is cached
     */
    boolean contains(GroupArtifactVersion gav);
    
    /**
     * Remove artifact from cache
     * @param gav Group:Artifact:Version coordinate
     */
    void remove(GroupArtifactVersion gav);
    
    /**
     * Clear all cached artifacts
     */
    void clear();
    
    /**
     * Get cache statistics
     * @return Cache statistics information
     */
    CacheStats getStats();
}

MavenPomCache

Interface for caching Maven POM files.

/**
 * Interface for caching Maven POM files to improve dependency resolution performance
 */
public interface MavenPomCache {
    /**
     * Get cached POM
     * @param gav Group:Artifact:Version coordinate
     * @return Cached POM or null if not cached
     */
    @Nullable Pom get(GroupArtifactVersion gav);
    
    /**
     * Cache POM
     * @param gav Group:Artifact:Version coordinate
     * @param pom POM to cache
     */
    void put(GroupArtifactVersion gav, Pom pom);
    
    /**
     * Check if POM is cached
     * @param gav Group:Artifact:Version coordinate  
     * @return true if POM is cached
     */
    boolean contains(GroupArtifactVersion gav);
    
    /**
     * Remove POM from cache
     * @param gav Group:Artifact:Version coordinate
     */
    void remove(GroupArtifactVersion gav);
    
    /**
     * Clear all cached POMs
     */
    void clear();
    
    /**
     * Get cache size information
     * @return Number of cached POMs
     */
    int size();
}

Artifact Cache Implementations

LocalMavenArtifactCache

File system-based artifact cache implementation.

/**
 * File system-based Maven artifact cache
 * Stores artifacts in local directory structure matching Maven repository layout
 */
public class LocalMavenArtifactCache implements MavenArtifactCache {
    /**
     * Create cache with default Maven local repository location
     */
    public LocalMavenArtifactCache();
    
    /**
     * Create cache with custom cache directory
     * @param cacheDirectory Directory to store cached artifacts
     */
    public LocalMavenArtifactCache(Path cacheDirectory);
    
    /**
     * Create cache with configuration
     * @param cacheDirectory Directory to store cached artifacts
     * @param maxSizeBytes Maximum cache size in bytes
     * @param ttlHours Time-to-live for cached artifacts in hours
     */
    public LocalMavenArtifactCache(Path cacheDirectory, long maxSizeBytes, int ttlHours);
}

Usage Examples:

// Use default Maven local repository
LocalMavenArtifactCache cache = new LocalMavenArtifactCache();

// Use custom cache directory
Path customCache = Paths.get("/opt/maven-cache");
LocalMavenArtifactCache customCache = new LocalMavenArtifactCache(customCache);

// Use with size and TTL limits
LocalMavenArtifactCache limitedCache = new LocalMavenArtifactCache(
    customCache,
    1024 * 1024 * 1024L, // 1GB max size
    24 * 7               // 1 week TTL
);

// Configure parser with cache
MavenParser parser = MavenParser.builder()
    .cache(cache)
    .build();

POM Cache Implementations

InMemoryMavenPomCache

In-memory POM cache implementation with LRU eviction.

/**
 * In-memory Maven POM cache with LRU eviction policy
 */
public class InMemoryMavenPomCache implements MavenPomCache {
    /**
     * Create cache with default capacity (1000 POMs)
     */
    public InMemoryMavenPomCache();
    
    /**
     * Create cache with custom capacity
     * @param maxEntries Maximum number of POMs to cache
     */
    public InMemoryMavenPomCache(int maxEntries);
    
    /**
     * Create cache with capacity and TTL
     * @param maxEntries Maximum number of POMs to cache
     * @param ttlMillis Time-to-live for cached POMs in milliseconds
     */
    public InMemoryMavenPomCache(int maxEntries, long ttlMillis);
}

RocksdbMavenPomCache

RocksDB-based persistent POM cache implementation.

/**
 * RocksDB-based persistent Maven POM cache
 * Provides high-performance persistent caching with compression
 */
public class RocksdbMavenPomCache implements MavenPomCache {
    /**
     * Create cache with default database location
     */
    public RocksdbMavenPomCache();
    
    /**
     * Create cache with custom database path
     * @param databasePath Path to RocksDB database directory
     */
    public RocksdbMavenPomCache(Path databasePath);
    
    /**
     * Create cache with configuration
     * @param databasePath Path to RocksDB database directory
     * @param compressionType Compression algorithm to use
     * @param maxBackgroundJobs Number of background compaction jobs
     */
    public RocksdbMavenPomCache(Path databasePath, CompressionType compressionType, int maxBackgroundJobs);
    
    /**
     * Close the database connection
     * Should be called when cache is no longer needed
     */
    public void close();
}

CompositeMavenPomCache

Composite cache supporting multiple cache backends with layering.

/**
 * Composite Maven POM cache that layers multiple cache implementations
 * Typically used with fast L1 cache (in-memory) and slower L2 cache (persistent)
 */
public class CompositeMavenPomCache implements MavenPomCache {
    /**
     * Create composite cache with multiple backends (ordered by priority)
     * @param caches Cache implementations in priority order (L1, L2, etc.)
     */
    public CompositeMavenPomCache(MavenPomCache... caches);
    
    /**
     * Create composite cache with configuration
     * @param caches Cache implementations in priority order
     * @param writeThrough Whether to write to all caches on put operations
     */
    public CompositeMavenPomCache(boolean writeThrough, MavenPomCache... caches);
}

Usage Examples:

// Simple in-memory cache
InMemoryMavenPomCache memoryCache = new InMemoryMavenPomCache(5000);

// Persistent RocksDB cache
Path dbPath = Paths.get("/opt/maven-pom-cache");
RocksdbMavenPomCache persistentCache = new RocksdbMavenPomCache(dbPath);

// Composite cache: fast memory + persistent storage
CompositeMavenPomCache compositeCache = new CompositeMavenPomCache(
    true, // write-through
    memoryCache,     // L1: fast in-memory
    persistentCache  // L2: persistent storage
);

// Configure parser with composite cache
MavenParser parser = MavenParser.builder()
    .pomCache(compositeCache)
    .build();

// Remember to close persistent caches
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    persistentCache.close();
}));

Cache Configuration

CacheStats

Cache statistics and monitoring information.

/**
 * Cache statistics for monitoring performance
 */
public class CacheStats {
    /**
     * Get cache hit count
     */
    public long getHitCount();
    
    /**
     * Get cache miss count
     */
    public long getMissCount();
    
    /**
     * Get cache hit rate (0.0 to 1.0)
     */
    public double getHitRate();
    
    /**
     * Get total cache requests
     */
    public long getRequestCount();
    
    /**
     * Get current cache size
     */
    public long getSize();
    
    /**
     * Get maximum cache size
     */
    public long getMaxSize();
    
    /**
     * Get eviction count
     */
    public long getEvictionCount();
    
    /**
     * Get average load time in nanoseconds
     */
    public double getAverageLoadPenalty();
}

Cache Event Listeners

/**
 * Interface for cache event notifications
 */
public interface CacheListener {
    /**
     * Called when item is added to cache
     */
    void onCacheHit(GroupArtifactVersion gav);
    
    /**
     * Called when item is not found in cache
     */
    void onCacheMiss(GroupArtifactVersion gav);
    
    /**
     * Called when item is evicted from cache
     */
    void onEviction(GroupArtifactVersion gav, Object value);
    
    /**
     * Called when cache is cleared
     */
    void onClear();
}

// Add listeners to cache implementations
public class MonitoredMavenPomCache implements MavenPomCache {
    public void addListener(CacheListener listener);
    public void removeListener(CacheListener listener);
}

Cache Integration with MavenParser

Cache-Aware Parser Configuration

/**
 * Configure MavenParser with caching for optimal performance
 */
public class MavenParser.Builder {
    /**
     * Set artifact cache for parser
     * @param cache Artifact cache implementation
     * @return Builder for chaining
     */
    public Builder cache(MavenArtifactCache cache);
    
    /**
     * Set POM cache for parser
     * @param cache POM cache implementation
     * @return Builder for chaining
     */
    public Builder pomCache(MavenPomCache cache);
    
    /**
     * Enable/disable caching entirely
     * @param enabled Whether to use caching
     * @return Builder for chaining
     */
    public Builder caching(boolean enabled);
}

Complete Cache Setup Example:

// Set up comprehensive caching strategy
Path cacheRoot = Paths.get(System.getProperty("user.home"), ".maven-rewrite-cache");

// L1: Fast in-memory cache for frequently accessed items
InMemoryMavenPomCache l1Cache = new InMemoryMavenPomCache(
    1000,           // 1000 POMs
    TimeUnit.HOURS.toMillis(1)  // 1 hour TTL
);

// L2: Persistent cache for long-term storage
RocksdbMavenPomCache l2Cache = new RocksdbMavenPomCache(
    cacheRoot.resolve("pom-cache"),
    CompressionType.LZ4_COMPRESSION,
    4  // 4 background compaction jobs
);

// Composite POM cache
CompositeMavenPomCache pomCache = new CompositeMavenPomCache(true, l1Cache, l2Cache);

// Artifact cache
LocalMavenArtifactCache artifactCache = new LocalMavenArtifactCache(
    cacheRoot.resolve("artifact-cache"),
    2L * 1024 * 1024 * 1024,  // 2GB max size
    24 * 7  // 1 week TTL
);

// Add monitoring
CacheListener monitor = new CacheListener() {
    @Override
    public void onCacheHit(GroupArtifactVersion gav) {
        System.out.println("Cache hit: " + gav);
    }
    
    @Override
    public void onCacheMiss(GroupArtifactVersion gav) {
        System.out.println("Cache miss: " + gav);
    }
    
    @Override
    public void onEviction(GroupArtifactVersion gav, Object value) {
        System.out.println("Cache eviction: " + gav);
    }
    
    @Override
    public void onClear() {
        System.out.println("Cache cleared");
    }
};

// Configure parser with caching
MavenParser parser = MavenParser.builder()
    .pomCache(pomCache)
    .cache(artifactCache)
    .build();

// Parse with caching benefits
ExecutionContext ctx = new InMemoryExecutionContext();
List<SourceFile> parsed = parser.parse(ctx, pomXmlContent);

// Monitor cache performance
CacheStats stats = artifactCache.getStats();
System.out.println("Artifact Cache Stats:");
System.out.println("  Hit Rate: " + String.format("%.2f%%", stats.getHitRate() * 100));
System.out.println("  Total Requests: " + stats.getRequestCount());
System.out.println("  Cache Size: " + stats.getSize());

// Clean up
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    l2Cache.close();
}));

Custom Cache Implementations

Implementing Custom Artifact Cache

/**
 * Example custom artifact cache implementation using external storage
 */
public class CloudMavenArtifactCache implements MavenArtifactCache {
    private final CloudStorageClient client;
    private final String bucketName;
    private final Map<GroupArtifactVersion, Long> accessTimes = new ConcurrentHashMap<>();
    
    public CloudMavenArtifactCache(CloudStorageClient client, String bucketName) {
        this.client = client;
        this.bucketName = bucketName;
    }
    
    @Override
    public @Nullable byte[] get(GroupArtifactVersion gav) {
        String key = keyFor(gav);
        try {
            byte[] data = client.getObject(bucketName, key);
            accessTimes.put(gav, System.currentTimeMillis());
            return data;
        } catch (ObjectNotFoundException e) {
            return null;
        }
    }
    
    @Override
    public void put(GroupArtifactVersion gav, byte[] artifact) {
        String key = keyFor(gav);
        client.putObject(bucketName, key, artifact);
        accessTimes.put(gav, System.currentTimeMillis());
    }
    
    private String keyFor(GroupArtifactVersion gav) {
        return gav.getGroupId().replace('.', '/') + "/" +
               gav.getArtifactId() + "/" +
               gav.getVersion() + "/" +
               gav.getArtifactId() + "-" + gav.getVersion() + ".jar";
    }
    
    // Implement other interface methods...
}

Implementing Custom POM Cache

/**
 * Example custom POM cache with Redis backend
 */
public class RedisMavenPomCache implements MavenPomCache {
    private final RedisClient redis;
    private final ObjectMapper objectMapper;
    private final Duration ttl;
    
    public RedisMavenPomCache(RedisClient redis, Duration ttl) {
        this.redis = redis;
        this.ttl = ttl;
        this.objectMapper = new ObjectMapper();
    }
    
    @Override
    public @Nullable Pom get(GroupArtifactVersion gav) {
        String key = keyFor(gav);
        String json = redis.get(key);
        if (json != null) {
            try {
                return objectMapper.readValue(json, Pom.class);
            } catch (JsonProcessingException e) {
                // Log error and return null
                return null;
            }
        }
        return null;
    }
    
    @Override
    public void put(GroupArtifactVersion gav, Pom pom) {
        String key = keyFor(gav);
        try {
            String json = objectMapper.writeValueAsString(pom);
            redis.setex(key, ttl.getSeconds(), json);
        } catch (JsonProcessingException e) {
            // Log error
        }
    }
    
    private String keyFor(GroupArtifactVersion gav) {
        return "maven:pom:" + gav.getGroupId() + ":" + gav.getArtifactId() + ":" + gav.getVersion();
    }
    
    // Implement other interface methods...
}

Install with Tessl CLI

npx tessl i tessl/maven-org-openrewrite--rewrite-maven

docs

caching.md

core-parsing.md

data-model.md

index.md

recipes.md

search-analysis.md

utilities.md

tile.json