Extract @ipp/core npm workspace package
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
|
||||
import express from 'express'
|
||||
import type { Server } from 'http'
|
||||
import type { AddressInfo } from 'net'
|
||||
import { asyncHandler, errorHandler } from '../src/http'
|
||||
|
||||
/*
|
||||
Regression tests for the per-request crash class: under Express 4 a rejected
|
||||
promise in an async route became an unhandledRejection, and index.ts used to
|
||||
respond to that with process.exit(1) - one bad request took down the whole
|
||||
container. asyncHandler + errorHandler must instead turn any thrown/rejected
|
||||
route error into a plain 404 (the privacy policy: no upstream detail) while
|
||||
the server keeps serving.
|
||||
*/
|
||||
|
||||
describe('asyncHandler + errorHandler', () => {
|
||||
let server: Server
|
||||
let base: string
|
||||
|
||||
beforeAll(async () => {
|
||||
// Silence errorHandler's expected server-side logging during these tests
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
|
||||
const app = express()
|
||||
app.get('/ok', asyncHandler(async (_req, res) => { res.send('ok') }))
|
||||
app.get('/boom', asyncHandler(async () => {
|
||||
throw new TypeError("Cannot read properties of undefined (reading 'headers')")
|
||||
}))
|
||||
app.get('/mid-stream', asyncHandler(async (_req, res) => {
|
||||
res.status(200)
|
||||
res.write('partial')
|
||||
throw new Error('upstream died mid-response')
|
||||
}))
|
||||
app.use(errorHandler)
|
||||
|
||||
await new Promise<void>(resolve => {
|
||||
server = app.listen(0, resolve)
|
||||
})
|
||||
base = 'http://127.0.0.1:' + (server.address() as AddressInfo).port
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
server?.close()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('turns a rejected route promise into a 404 with an empty body', async () => {
|
||||
const res = await fetch(base + '/boom')
|
||||
expect(res.status).toBe(404)
|
||||
expect(await res.text()).toBe('')
|
||||
})
|
||||
|
||||
it('keeps serving other requests after a route has thrown', async () => {
|
||||
await fetch(base + '/boom')
|
||||
const res = await fetch(base + '/ok')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toBe('ok')
|
||||
})
|
||||
|
||||
it('does not leak error detail to the client', async () => {
|
||||
const res = await fetch(base + '/boom')
|
||||
const body = await res.text()
|
||||
expect(body).not.toContain('TypeError')
|
||||
expect(body).not.toContain('headers')
|
||||
})
|
||||
|
||||
it('ends the response when the error hits after headers were sent', async () => {
|
||||
const res = await fetch(base + '/mid-stream')
|
||||
// Status was already committed before the throw; the handler can only
|
||||
// end the stream, not rewrite it to a 404.
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toBe('partial')
|
||||
// And the server is still alive afterwards
|
||||
const ok = await fetch(base + '/ok')
|
||||
expect(ok.status).toBe(200)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { getImmichVersion, isImmichVersionSupported, MIN_IMMICH_VERSION } from '../src/immich/client'
|
||||
|
||||
// The startup guard that refuses to run against an Immich server older than
|
||||
// IPP supports. The floor is 2.0.0 - the columnar timeline API IPP relies on
|
||||
// to enumerate album shares landed in Immich 2.0.
|
||||
|
||||
function jsonResponse (body: unknown, status = 200) {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
headers: { get: (h: string) => (h.toLowerCase() === 'content-type' ? 'application/json' : null) },
|
||||
json: async () => body,
|
||||
text: async () => JSON.stringify(body)
|
||||
}
|
||||
}
|
||||
|
||||
describe('isImmichVersionSupported', () => {
|
||||
it('accepts exactly the minimum version', () => {
|
||||
expect(isImmichVersionSupported(MIN_IMMICH_VERSION)).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts newer major/minor/patch across the 2.x and 3.x lines', () => {
|
||||
expect(isImmichVersionSupported({ major: 2, minor: 7, patch: 5 })).toBe(true)
|
||||
expect(isImmichVersionSupported({ major: 3, minor: 0, patch: 2 })).toBe(true)
|
||||
expect(isImmichVersionSupported({ major: 4, minor: 0, patch: 0 })).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects 1.x, which predates the columnar timeline API', () => {
|
||||
expect(isImmichVersionSupported({ major: 1, minor: 137, patch: 3 })).toBe(false)
|
||||
expect(isImmichVersionSupported({ major: 1, minor: 125, patch: 7 })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getImmichVersion', () => {
|
||||
beforeEach(() => {
|
||||
process.env.IMMICH_URL = 'http://immich.test'
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('parses the /server/version response', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async (url: string) => {
|
||||
if (url.includes('/server/version')) return jsonResponse({ major: 3, minor: 0, patch: 2, prerelease: null })
|
||||
throw new Error('Unexpected fetch to ' + url)
|
||||
}))
|
||||
expect(await getImmichVersion()).toEqual({ major: 3, minor: 0, patch: 2 })
|
||||
})
|
||||
|
||||
it('returns null when Immich is unreachable', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ECONNREFUSED') }))
|
||||
expect(await getImmichVersion()).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null on an unexpected response shape', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ version: 'v3.0.2' })))
|
||||
expect(await getImmichVersion()).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { loadConfig } from '../src/config/loader'
|
||||
import { getNumericConfigOption } from '../src/config/access'
|
||||
|
||||
/*
|
||||
Regression tests for the non-numeric config bug: a non-numeric
|
||||
`ipp.downloadFromImmichConcurrencyLimit` used to reach its consumer as NaN,
|
||||
where `active >= NaN` is always false - so the download concurrency limit
|
||||
never throttled and every asset in a zip download hit Immich at once.
|
||||
*/
|
||||
|
||||
function loadConfigFrom (config: Record<string, unknown>) {
|
||||
process.env.CONFIG = JSON.stringify(config)
|
||||
loadConfig()
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.CONFIG
|
||||
loadConfig()
|
||||
})
|
||||
|
||||
describe('getNumericConfigOption', () => {
|
||||
it('returns a configured number', () => {
|
||||
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: 5 } })
|
||||
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(5)
|
||||
})
|
||||
|
||||
it('coerces a numeric string (docker-compose env values arrive as strings)', () => {
|
||||
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: '5' } })
|
||||
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(5)
|
||||
})
|
||||
|
||||
it('falls back to the default for a non-numeric value instead of NaN', () => {
|
||||
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: 'lots' } })
|
||||
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(20)
|
||||
})
|
||||
|
||||
it('falls back to the default for non-scalar values', () => {
|
||||
loadConfigFrom({ ipp: { downloadFromImmichConcurrencyLimit: { max: 5 } } })
|
||||
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(20)
|
||||
})
|
||||
|
||||
it('falls back to the default when the option is unset', () => {
|
||||
loadConfigFrom({})
|
||||
expect(getNumericConfigOption('ipp.downloadFromImmichConcurrencyLimit', 20)).toBe(20)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { escapeHtml, jsonForInlineScript } from '../src/utils/text'
|
||||
|
||||
describe('escapeHtml', () => {
|
||||
it('escapes the five HTML-significant characters', () => {
|
||||
expect(escapeHtml('<script>alert("xss")</script>')).toBe(
|
||||
'<script>alert("xss")</script>'
|
||||
)
|
||||
})
|
||||
|
||||
it('escapes ampersand first so other escapes are not re-escaped', () => {
|
||||
expect(escapeHtml('&')).toBe('&amp;')
|
||||
})
|
||||
|
||||
it('escapes single quotes', () => {
|
||||
expect(escapeHtml("it's")).toBe('it's')
|
||||
})
|
||||
|
||||
it('returns empty string unchanged', () => {
|
||||
expect(escapeHtml('')).toBe('')
|
||||
})
|
||||
|
||||
it('passes through strings with no special characters', () => {
|
||||
expect(escapeHtml('plain text 123')).toBe('plain text 123')
|
||||
})
|
||||
})
|
||||
|
||||
describe('jsonForInlineScript', () => {
|
||||
it('escapes < so </script> cannot terminate an inline script block', () => {
|
||||
const out = jsonForInlineScript({ name: '</script><script>alert(1)</script>' })
|
||||
expect(out).not.toContain('<')
|
||||
expect(out).toContain('\\u003c/script>')
|
||||
})
|
||||
|
||||
it('round-trips through JSON.parse unchanged', () => {
|
||||
const value = {
|
||||
name: '</script> & <!-- tricky --> \u2028\u2029',
|
||||
n: 3,
|
||||
nested: { arr: [1, 'two'] }
|
||||
}
|
||||
expect(JSON.parse(jsonForInlineScript(value))).toEqual(value)
|
||||
})
|
||||
|
||||
it('escapes the JS line separators U+2028 and U+2029', () => {
|
||||
const out = jsonForInlineScript({ s: '\u2028\u2029' })
|
||||
expect(out).toBe('{"s":"\\u2028\\u2029"}')
|
||||
})
|
||||
|
||||
it('matches JSON.stringify for benign values', () => {
|
||||
const value = { a: 1, b: 'plain text', c: null }
|
||||
expect(jsonForInlineScript(value)).toBe(JSON.stringify(value))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { TtlLruCache } from '../src/utils/ttlLruCache'
|
||||
|
||||
/*
|
||||
All TTL-based assertions rely on Vitest's fake-timer system mocking
|
||||
`Date.now()`. `vi.advanceTimersByTime` advances both the timer queue
|
||||
and the system clock the cache reads from.
|
||||
*/
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('TtlLruCache', () => {
|
||||
it('returns undefined for an unknown key', () => {
|
||||
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
|
||||
expect(cache.get('missing')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns the value after set', () => {
|
||||
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
|
||||
cache.set('a', 'apple')
|
||||
expect(cache.get('a')).toBe('apple')
|
||||
})
|
||||
|
||||
it('returns undefined exactly at the TTL boundary', () => {
|
||||
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
|
||||
cache.set('a', 'apple')
|
||||
vi.advanceTimersByTime(999)
|
||||
expect(cache.get('a')).toBe('apple')
|
||||
vi.advanceTimersByTime(1)
|
||||
expect(cache.get('a')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops expired entries on access so they do not count toward the size cap', () => {
|
||||
const cache = new TtlLruCache<string>({ ttlMs: 100, max: 2 })
|
||||
cache.set('a', '1')
|
||||
vi.advanceTimersByTime(200)
|
||||
// Read once so the expired entry is dropped from the internal map.
|
||||
expect(cache.get('a')).toBeUndefined()
|
||||
// The cache should now have capacity for two fresh entries with no
|
||||
// collateral eviction of either.
|
||||
cache.set('b', '2')
|
||||
cache.set('c', '3')
|
||||
expect(cache.get('b')).toBe('2')
|
||||
expect(cache.get('c')).toBe('3')
|
||||
})
|
||||
})
|
||||
|
||||
describe('TtlLruCache delete', () => {
|
||||
it('removes an existing entry', () => {
|
||||
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
|
||||
cache.set('a', '1')
|
||||
cache.delete('a')
|
||||
expect(cache.get('a')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('is a no-op for a missing key', () => {
|
||||
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
|
||||
expect(() => cache.delete('missing')).not.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('TtlLruCache LRU eviction', () => {
|
||||
it('evicts the oldest entry when set causes overflow', () => {
|
||||
const cache = new TtlLruCache<string>({ ttlMs: 10_000, max: 2 })
|
||||
cache.set('a', '1')
|
||||
cache.set('b', '2')
|
||||
cache.set('c', '3') // overflow - 'a' is the oldest, gets evicted
|
||||
expect(cache.get('a')).toBeUndefined()
|
||||
expect(cache.get('b')).toBe('2')
|
||||
expect(cache.get('c')).toBe('3')
|
||||
})
|
||||
|
||||
it('get refreshes LRU position so a recently-read entry survives eviction', () => {
|
||||
const cache = new TtlLruCache<string>({ ttlMs: 10_000, max: 2 })
|
||||
cache.set('a', '1')
|
||||
cache.set('b', '2')
|
||||
// Touch 'a' so it becomes the most-recently-used. 'b' is now oldest.
|
||||
cache.get('a')
|
||||
cache.set('c', '3') // overflow - 'b' should be evicted, not 'a'
|
||||
expect(cache.get('a')).toBe('1')
|
||||
expect(cache.get('b')).toBeUndefined()
|
||||
expect(cache.get('c')).toBe('3')
|
||||
})
|
||||
})
|
||||
|
||||
describe('TtlLruCache re-set', () => {
|
||||
it('replaces the value when set is called twice for the same key', () => {
|
||||
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
|
||||
cache.set('a', '1')
|
||||
cache.set('a', '2')
|
||||
expect(cache.get('a')).toBe('2')
|
||||
})
|
||||
|
||||
it('resets the TTL on re-set', () => {
|
||||
const cache = new TtlLruCache<string>({ ttlMs: 1000, max: 10 })
|
||||
cache.set('a', '1')
|
||||
vi.advanceTimersByTime(800)
|
||||
cache.set('a', '2') // bumps expiry to 1000ms from now
|
||||
vi.advanceTimersByTime(800)
|
||||
// 800 + 800 = 1600ms past the original set, but only 800ms past the
|
||||
// re-set, so the entry should still be live.
|
||||
expect(cache.get('a')).toBe('2')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user