// src/index.ts (Main Service Code)
// Compile with `npm run build` for production.
import express, { Request, Response, NextFunction } from 'express';
import { DateTime, Settings } from 'luxon';
import { createLogger, format, transports } from 'winston';
import LRU from 'lru-cache';
import Redis from 'ioredis';
import rateLimit from 'express-rate-limit';
import client from 'prom-client';
import cors from 'cors';
import helmet from 'helmet';
import { z } from 'zod';
// Config
const CONFIG = {
PORT: (process.env.PORT || 3000) as number,
REDIS_URL: process.env.REDIS_URL || undefined,
CACHE_TTL_MS: parseInt(process.env.CACHE_TTL_MS || '3600000'), // 1hr
RATE_LIMIT_WINDOW_MS: 15 * 60 * 1000, // 15min
RATE_LIMIT_MAX: 1000, // per IP
MAX_TIMESTAMP_AGE_YEARS: 100, // Mitigate drift on absurd timestamps
};
// Prometheus Metrics
const register = new client.Registry();
register.setDefaultLabels({ app: 'time-format-service' });
const httpRequests = new client.Counter({
name: 'http_requests_total',
help: 'Total HTTP requests',
labelNames: ['method', 'route', 'status'],
});
const cacheHits = new client.Counter({ name: 'cache_hits_total', help: 'Cache hits' });
const cacheMisses = new client.Counter({ name: 'cache_misses_total', help: 'Cache misses' });
register.registerMetric(httpRequests);
register.registerMetric(cacheHits);
register.registerMetric(cacheMisses);
const metricsMiddleware = async (req: Request, res: Response, next: NextFunction) => {
res.on('finish', () => {
httpRequests.inc({ method: req.method, route: req.route?.path || req.path, status: res.statusCode });
});
next();
};
// Logging
const logger = createLogger({
level: 'info',
format: format.combine(format.timestamp(), format.json()),
transports: [new transports.Console()],
});
// Caching: Hybrid LRU + Redis
let cache: LRU<string, string> | null = null;
let redis: Redis | null = null;
if (CONFIG.REDIS_URL) {
redis = new Redis(CONFIG.REDIS_URL);
redis.on('error', (err) => logger.error('Redis error', { err }));
} else {
cache = new LRU<string, string>({ max: 10000, ttl: CONFIG.CACHE_TTL_MS });
}
async function getCache(key: string): Promise<string | undefined> {
if (redis) {
try {
const val = await redis.get(key);
if (val) cacheHits.inc();
return val;
} catch (err) {
logger.warn('Redis get failed, fallback to LRU', { err });
}
}
if (cache) {
const val = cache.get(key);
if (val) cacheHits.inc();
return val;
}
return undefined;
}
async function setCache(key: string, value: string): Promise<void> {
if (redis) {
try {
await redis.setex(key, CONFIG.CACHE_TTL_MS / 1000, value);
} catch (err) {
logger.warn('Redis set failed', { err });
}
}
if (cache) {
cache.set(key, value);
}
}
// IANA Timezone Data: Load valid list (cached at startup)
const VALID_TZ_FILE = new URL('../iana-timezones.json', import.meta.url).pathname; // Embed or fetch
// Note: Download from https://github.com/eggert/tz/blob/main/backward -> parse to JSON list
// For demo, assume embedded JSON with ~600 entries.
let validTimezones: Set<string> = new Set(); // Populate at startup
async function loadValidTimezones(): Promise<void> {
// Simulated load (replace with fs.readFileSync(VALID_TZ_FILE, 'utf8') and JSON.parse)
// Real impl: curl -s https://raw.githubusercontent.com/iamtokra/iana-tz-data/master/iana-tz-data-public.json | jq -r '.[].name'
const tzList = ['UTC', 'America/New_York', 'Europe/London', 'Asia/Tokyo' /* ... full 600+ */];
validTimezones = new Set(tzList);
logger.info('Loaded IANA timezones', { count: tzList.length });
}
await loadValidTimezones();
// Luxon Settings: Ensure UTC zone for consistency
Settings.defaultZone = 'UTC';
// Input Validation Schemas (Zod)
const FormatRequestSchema = z.object({
timestamp: z.number().int().refine(ts => {
const dt = DateTime.fromSeconds(ts);
return dt.isValid && Math.abs(dt.diffNow('years').years) < CONFIG.MAX_TIMESTAMP_AGE_YEARS;
}, { message: 'Invalid UTC Unix timestamp (±100 years)' }),
timezone: z.string().min(1).refine(tz => validTimezones.has(tz), { message: 'Invalid IANA timezone' }),
format: z.string().default('yyyy-MM-dd HH:mm:ss ZZZZ').refine(fmt => {
try { DateTime.now().toFormat(fmt); return true; } catch { return false; }
}, { message: 'Invalid Luxon format' }),
});
// Express App
const app = express();
app.use(helmet()); // Security headers
app.use(cors());
app.use(express.json({ limit: '1kb' }));
app.use(metricsMiddleware);
// Rate Limiting
const limiter = rateLimit({ windowMs: CONFIG.RATE_LIMIT_WINDOW_MS, max: CONFIG.RATE_LIMIT_MAX });
app.use('/format', limiter);
// Health Check
app.get('/health', (req, res) => res.json({ status: 'ok', uptime: process.uptime() }));
app.get('/metrics', async (req, res) => res.set('Content-Type', register.contentType).send(await register.metrics()));
// Format Endpoint (POST for flexibility)
app.post('/format', async (req: Request, res: Response) => {
try {
const { timestamp, timezone, format } = FormatRequestSchema.parse(req.body);
const cacheKey = `${timestamp}-${timezone}-${format}`;
// Check cache
let result = await getCache(cacheKey);
if (result) {
logger.info('Cache hit', { key: cacheKey });
return res.json({ formatted: result, fromCache: true });
}
cacheMisses.inc();
// Compute with Luxon (DST-safe)
const dt = DateTime.fromSeconds(timestamp, { zone: timezone });
if (!dt.isValid) {
return res.status(400).json({ error: 'Invalid date after TZ conversion' });
}
result = dt.toFormat(format);
// Cache result
await setCache(cacheKey, result);
logger.info('Computed & cached', { key: cacheKey, timezone, offset: dt.offsetName });
res.json({ formatted: result, fromCache: false, offset: dt.offsetName, isDST: dt.isInDST });
} catch (err) {
if (err instanceof z.ZodError) {
return res.status(400).json({ error: 'Validation failed', details: err.errors });
}
logger.error('Format error', { err });
res.status(500).json({ error: 'Internal error' });
}
});
// GET /format?timestamp=1696152000&timezone=America/New_York&format=yyyy-MM-dd HH:mm:ss z
app.get('/format', async (req: Request, res: Response) => {
try {
const { timestamp, timezone, format } = FormatRequestSchema.parse({
timestamp: parseInt(req.query.timestamp as string),
timezone: req.query.timezone as string,
format: req.query.format as string,
});
// Reuse POST logic via cache key
const cacheKey = `${timestamp}-${timezone}-${format}`;
let result = await getCache(cacheKey);
if (!result) {
cacheMisses.inc();
const dt = DateTime.fromSeconds(timestamp, { zone: timezone });
if (!dt.isValid) throw new Error('Invalid date');
result = dt.toFormat(format);
await setCache(cacheKey, result);
} else {
cacheHits.inc();
}
res.json({ formatted: result });
} catch (err) {
if (err instanceof z.ZodError) {
return res.status(400).json({ error: 'Validation failed', details: err.errors });
}
res.status(500).json({ error: 'Internal error' });
}
});
// Timezone List Endpoint
app.get('/timezones', (req, res) => {
res.json({ timezones: Array.from(validTimezones).sort() });
});
// Graceful Shutdown
process.on('SIGTERM', async () => {
logger.info('Shutting down');
if (redis) await redis.quit();
process.exit(0);
});
app.listen(CONFIG.PORT, () => {
logger.info('Time Format Service started', { port: CONFIG.PORT, redis: !!CONFIG.REDIS_URL });
});