Skip to content
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
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ jobs:
run: |
npm run start:backend &
npm run build:test-app
npm run e2e
npm run e2e -w apps/cache-testing
- uses: actions/upload-artifact@v4
if: always()
with:
Expand Down
10 changes: 9 additions & 1 deletion .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
{
"recommendations": ["biomejs.biome", "dbaeumer.vscode-eslint", "esbenp.prettier-vscode", "unifiedjs.vscode-mdx"]
"recommendations": [
"biomejs.biome",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"unifiedjs.vscode-mdx",
"Vercel.turbo-vsc",
"ms-playwright.playwright",
"streetsidesoftware.code-spell-checker"
]
}
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,6 @@
"[typescriptreact]": {
"editor.defaultFormatter": "biomejs.biome"
},
"grammarly.files.include": ["**/*.md", "**/*.mdx"]
"grammarly.files.include": ["**/*.md", "**/*.mdx"],
"turbo.useLocalTurbo": true
}
5 changes: 5 additions & 0 deletions apps/cache-testing-15-app/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
REDIS_URL=redis://localhost:6379
REMOTE_CACHE_SERVER_BASE_URL=http://localhost:8080
HOSTNAME=localhost
PPR_ENABLED=false
NEXT_PRIVATE_DEBUG_CACHE=1
10 changes: 10 additions & 0 deletions apps/cache-testing-15-app/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/** @type {import("eslint").Linter.Config} */
module.exports = {
root: true,
extends: ['@repo/eslint-config/next.js'],
parser: '@typescript-eslint/parser',
parserOptions: {
project: true,
},
ignorePatterns: ['*.mjs'],
};
Empty file.
14 changes: 14 additions & 0 deletions apps/cache-testing-15-app/cache-handler-local.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// @ts-check

import { CacheHandler } from '@neshca/cache-handler';
import createLruHandler from '@neshca/cache-handler/local-lru';

CacheHandler.onCreation(() => {
const localHandler = createLruHandler();

return {
handlers: [localHandler],
};
});

export default CacheHandler;
35 changes: 35 additions & 0 deletions apps/cache-testing-15-app/cache-handler-next-example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const cache = new Map();

module.exports = class CacheHandler {
constructor(options) {
this.options = options;
}

// biome-ignore lint/suspicious/useAwait: don't bother
async get(key) {
// This could be stored anywhere, like durable storage
return cache.get(key);
}

// biome-ignore lint/suspicious/useAwait: don't bother
async set(key, data, ctx) {
// This could be stored anywhere, like durable storage
cache.set(key, {
value: data,
lastModified: Date.now(),
tags: ctx.tags,
});
}

// biome-ignore lint/suspicious/useAwait: don't bother
async revalidateTag(tag) {
// Iterate over all entries in the cache
// biome-ignore lint/style/useConst: don't bother
for (let [key, value] of cache) {
// If the value's tags include the specified tag, delete this entry
if (value.tags.includes(tag)) {
cache.delete(key);
}
}
}
};
80 changes: 80 additions & 0 deletions apps/cache-testing-15-app/cache-handler-redis-stack.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// @ts-check

const { CacheHandler } = require('@neshca/cache-handler');
const createLruHandler = require('@neshca/cache-handler/local-lru').default;
const createRedisHandler = require('@neshca/cache-handler/redis-stack').default;
const { createClient } = require('redis');

CacheHandler.onCreation(async () => {
if (!process.env.REDIS_URL) {
console.warn('Make sure that REDIS_URL is added to the .env.local file and loaded properly.');
}

let client;

try {
// Create a Redis client.
client = createClient({
url: process.env.REDIS_URL,
name: `cache-handler:${process.env.PORT ?? process.pid}`,
});

// Redis won't work without error handling. https://github.com/redis/node-redis?tab=readme-ov-file#events
client.on('error', (error) => {
if (typeof process.env.NEXT_PRIVATE_DEBUG_CACHE !== 'undefined') {
console.error('Redis client error:', error);
}
});
} catch (error) {
console.warn('Failed to create Redis client:', error);
}

if (client) {
try {
console.info('Connecting Redis client...');

// Wait for the client to connect.
// Caveat: This will block the server from starting until the client is connected.
// And there is no timeout. Make your own timeout if needed.
await client.connect();
console.info('Redis client connected.');
} catch (error) {
console.warn('Failed to connect Redis client:', error);

console.warn('Disconnecting the Redis client...');
// Try to disconnect the client to stop it from reconnecting.
client
.disconnect()
.then(() => {
console.info('Redis client disconnected.');
})
.catch(() => {
console.warn('Failed to quit the Redis client after failing to connect.');
});
}
}

/** @type {import("@neshca/cache-handler").Handler | null} */
let handler;

if (client) {
// Create the `redis-stack` Handler if the client is available.
handler = createRedisHandler({
client,
keyPrefix: 'JSON:',
timeoutMs: 1000,
});
} else {
// Fallback to LRU handler if Redis client is not available.
// The application will still work, but the cache will be in-memory only and not shared.
handler = createLruHandler();
console.warn('Falling back to LRU handler because Redis client is not available.');
}

return {
handlers: [handler],
ttl: { defaultStaleAge: 60, estimateExpireAge: (staleAge) => staleAge * 2 },
};
});

module.exports = CacheHandler;
80 changes: 80 additions & 0 deletions apps/cache-testing-15-app/cache-handler-redis-stack.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// @ts-check

import { CacheHandler } from '@neshca/cache-handler';
import createLruHandler from '@neshca/cache-handler/local-lru';
import createRedisHandler from '@neshca/cache-handler/redis-stack';
import { createClient } from 'redis';

CacheHandler.onCreation(async () => {
if (!process.env.REDIS_URL) {
console.warn('Make sure that REDIS_URL is added to the .env.local file and loaded properly.');
}

let client;

try {
// Create a Redis client.
client = createClient({
url: process.env.REDIS_URL,
name: `cache-handler:${process.env.PORT ?? process.pid}`,
});

// Redis won't work without error handling. https://github.com/redis/node-redis?tab=readme-ov-file#events
client.on('error', (error) => {
if (typeof process.env.NEXT_PRIVATE_DEBUG_CACHE !== 'undefined') {
console.error('Redis client error:', error);
}
});
} catch (error) {
console.warn('Failed to create Redis client:', error);
}

if (client) {
try {
console.info('Connecting Redis client...');

// Wait for the client to connect.
// Caveat: This will block the server from starting until the client is connected.
// And there is no timeout. Make your own timeout if needed.
await client.connect();
console.info('Redis client connected.');
} catch (error) {
console.warn('Failed to connect Redis client:', error);

console.warn('Disconnecting the Redis client...');
// Try to disconnect the client to stop it from reconnecting.
client
.disconnect()
.then(() => {
console.info('Redis client disconnected.');
})
.catch(() => {
console.warn('Failed to quit the Redis client after failing to connect.');
});
}
}

/** @type {import("@neshca/cache-handler").Handler | null} */
let handler;

if (client) {
// Create the `redis-stack` Handler if the client is available.
handler = createRedisHandler({
client,
keyPrefix: 'JSON:',
timeoutMs: 1000,
});
} else {
// Fallback to LRU handler if Redis client is not available.
// The application will still work, but the cache will be in-memory only and not shared.
handler = createLruHandler();
console.warn('Falling back to LRU handler because Redis client is not available.');
}

return {
handlers: [handler],
ttl: { defaultStaleAge: 60, estimateExpireAge: (staleAge) => staleAge * 2 },
};
});

export default CacheHandler;
42 changes: 42 additions & 0 deletions apps/cache-testing-15-app/cache-handler-redis-strings.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// @ts-check

import { CacheHandler } from '@neshca/cache-handler';
import createRedisHandler from '@neshca/cache-handler/redis-strings';
import { createClient } from 'redis';

CacheHandler.onCreation(async () => {
if (!process.env.REDIS_URL) {
console.warn('Make sure that REDIS_URL is added to the .env.local file and loaded properly.');
}

const PREFIX = 'string:';

/** @type {import("redis").RedisClientType} */
const client = createClient({
url: process.env.REDIS_URL,
name: `cache-handler:${PREFIX}${process.env.PORT ?? process.pid}`,
});

// Redis won't work without error handling. https://github.com/redis/node-redis?tab=readme-ov-file#events
client.on('error', (error) => {
if (typeof process.env.NEXT_PRIVATE_DEBUG_CACHE !== 'undefined') {
console.error('Redis client error:', error);
}
});

console.info('Connecting Redis client...');
await client.connect();
console.info('Redis client connected.');

const redisHandler = createRedisHandler({
client,
keyPrefix: PREFIX,
});

return {
handlers: [redisHandler],
ttl: { defaultStaleAge: 60, estimateExpireAge: (staleAge) => staleAge * 2 },
};
});

export default CacheHandler;
16 changes: 16 additions & 0 deletions apps/cache-testing-15-app/cluster.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module.exports = {
apps: [
{
name: 'app',
script: '.next/__instances/3000/server.js',
instances: 2,
exec_mode: 'cluster',
env_production: {
NODE_ENV: 'production',
HOSTNAME: 'localhost',
REDIS_URL: 'redis://localhost:6379',
SERVER_STARTED: '1',
},
},
],
};
41 changes: 41 additions & 0 deletions apps/cache-testing-15-app/create-instances.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#!/bin/bash

# Set common paths
STANDALONE_DIR="$PWD/.next/standalone"
APP_DIR="$STANDALONE_DIR/apps/cache-testing-15-app"
PUBLIC_DIR="$PWD/public"
STATIC_DIR="$PWD/.next/static"
FETCH_CACHE_DIR="$PWD/.next/cache/fetch-cache"
INSTANCES_DIR="$PWD/.next/__instances"

copy_dir() {
if ! cp -r "$1" "$2"; then
echo "Failed to copy from $1 to $2"
exit 1
fi
}

# Copy public directory to standalone app directory
copy_dir "$PUBLIC_DIR/" "$APP_DIR/public"

# Copy static directory to standalone app/.next directory
copy_dir "$STATIC_DIR/" "$APP_DIR/.next/static"

# Copy fetch cache directory to standalone app/.next directory
mkdir -p "$APP_DIR/.next/cache/fetch-cache/"
cp $FETCH_CACHE_DIR/* $APP_DIR/.next/cache/fetch-cache/

create_instance_dir() {
if ! mkdir -p "$INSTANCES_DIR/$1"; then
echo "Failed to create $INSTANCES_DIR/$1 directory"
exit 1
fi
}

# Create instance directories
create_instance_dir 3000
create_instance_dir 3001

# Copy files from standalone directory to instance directories
copy_dir "$STANDALONE_DIR/." "$INSTANCES_DIR/3000"
copy_dir "$STANDALONE_DIR/." "$INSTANCES_DIR/3001"
22 changes: 22 additions & 0 deletions apps/cache-testing-15-app/next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// @ts-check

import path from 'node:path';

const cacheHandler = path.resolve('./cache-handler-redis-stack.mjs');

/** @type {import('next').NextConfig} */
const nextConfig = {
poweredByHeader: false,
reactStrictMode: true,
output: 'standalone',
cacheHandler: process.env.NODE_ENV !== 'development' ? cacheHandler : undefined,
cacheMaxMemorySize: 0, // disable default in-memory caching
outputFileTracingRoot: path.join(import.meta.dirname, '../../'),
experimental: {
// PPR should only be configured via the PPR_ENABLED env variable due to conditional logic in tests.
ppr: process.env.PPR_ENABLED === 'true',
largePageDataBytes: 1024 * 1024, // 1MB
},
};

export default nextConfig;
Loading