fix(storage): use wall-clock TTL and half-lifetime margin for presigned URL cache (#541)

* fix(storage): use wall-clock TTL and half-lifetime margin for presigned URL cache

* test(e2e): eliminate offline race in uploader resilience harness test
This commit is contained in:
Yiling-J
2026-11-23 13:39:31 +08:00
committed by GitHub
parent eeb41fee03
commit db628e65fa
6 changed files with 160 additions and 12 deletions
+1
View File
@@ -12,6 +12,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Fixed
- **storage**: Fix an issue where cached media preview and file URLs could expire and break after the host machine slept or near the end of an S3 link's lifetime.
- **search**: Video segment matches in Semantic Search and Find Similar show the segment’s first frame and let you scrub through it on hover. Matches that span the entire video reuse its full preview when available.
### Changed
+24
View File
@@ -48,6 +48,30 @@ describe('LruTtlCache', () => {
expect(cache.size).toBe(0)
})
it('should expire items using wall-clock time even when performance.now pauses during sleep', () => {
vi.useRealTimers()
let wallNow = 1_700_000_000_000
let perfNow = 1_000
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => wallNow)
const perfNowSpy = vi.spyOn(performance, 'now').mockImplementation(() => perfNow)
try {
const cache = new LruTtlCache<string, string>(10)
cache.set('key1', 'value1', 60_000)
expect(cache.get('key1')).toBe('value1')
// Simulate host sleep: wall clock advances past TTL while monotonic clock barely moves
wallNow += 120_000
perfNow += 500
expect(cache.get('key1')).toBeUndefined()
expect(cache.size).toBe(0)
} finally {
dateNowSpy.mockRestore()
perfNowSpy.mockRestore()
}
})
it('should proactively evict expired items on get', () => {
const sampleSize = 5
const cache = new LruTtlCache<string, string>(100, sampleSize)
+3 -2
View File
@@ -101,10 +101,11 @@ export class LruTtlCache<TKey, TValue> {
}
/**
* Monotonic time source to avoid issues with system clock jumps.
* Wall-clock time source so TTLs reflect real elapsed time across host sleep / VM suspend
* and stay aligned with wall-clock expirations such as presigned URL timestamps.
*/
private now(): number {
return performance.now()
return Date.now()
}
get size(): number {
+101
View File
@@ -101,6 +101,67 @@ describe('S3Service implementations', () => {
expect(getSignedUrlSpy).toHaveBeenCalledTimes(1)
})
it('should refresh cached default GET presign URLs after half their lifetime', async () => {
let wallNow = 1_700_000_000_000
let perfNow = 1_000
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => wallNow)
const perfNowSpy = vi.spyOn(performance, 'now').mockImplementation(() => perfNow)
try {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
getSignedUrlSpy.mockClear()
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-1')
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-2')
const url1 = await s3.presign('bucket', 'key', 'GET')
expect(url1).toBe('http://presigned-url-1')
// Default GET lifetime is 5h; before 2.5h the cached URL should still be reused
const almostHalfMs = 2.5 * 3600 * 1000 - 1_000
wallNow += almostHalfMs
perfNow += almostHalfMs
expect(await s3.presign('bucket', 'key', 'GET')).toBe('http://presigned-url-1')
expect(getSignedUrlSpy).toHaveBeenCalledTimes(1)
// Past 2.5h (half of the 5h lifetime), the cache must expire so callers never get nearly expired URLs
wallNow += 2_000
perfNow += 2_000
expect(await s3.presign('bucket', 'key', 'GET')).toBe('http://presigned-url-2')
expect(getSignedUrlSpy).toHaveBeenCalledTimes(2)
} finally {
dateNowSpy.mockRestore()
perfNowSpy.mockRestore()
}
})
it('should invalidate cached GET presign URLs after system sleep when wall clock advances but monotonic clock pauses', async () => {
let wallNow = 1_700_000_000_000
let perfNow = 1_000
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => wallNow)
const perfNowSpy = vi.spyOn(performance, 'now').mockImplementation(() => perfNow)
try {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
getSignedUrlSpy.mockClear()
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-1')
getSignedUrlSpy.mockResolvedValueOnce('http://presigned-url-2')
const url1 = await s3.presign('bucket', 'sleep-key', 'GET')
expect(url1).toBe('http://presigned-url-1')
// Simulate 15 hours of host sleep: wall clock jumps 15h while performance.now() barely moves
wallNow += 15 * 3600 * 1000
perfNow += 1_000
const url2 = await s3.presign('bucket', 'sleep-key', 'GET')
expect(url2).toBe('http://presigned-url-2')
expect(getSignedUrlSpy).toHaveBeenCalledTimes(2)
} finally {
dateNowSpy.mockRestore()
perfNowSpy.mockRestore()
}
})
it('signs with an explicit lifetime and caches it separately from the default', async () => {
const s3 = new S3StorageService('http://localhost:9000', 'key', 'secret', 'test-bucket')
getSignedUrlSpy.mockClear()
@@ -807,6 +868,46 @@ describe('S3Service implementations', () => {
expect(urlOther).not.toBe(url1)
})
it('should not return expired local GET presigned URLs after system sleep when wall clock advances but monotonic clock pauses', async () => {
let wallNow = 1_700_000_000_000
let perfNow = 1_000
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => wallNow)
const perfNowSpy = vi.spyOn(performance, 'now').mockImplementation(() => perfNow)
try {
const url1 = await localS3.presign('my-bucket', 'dir/sleep.png', 'GET')
const parsed1 = new URL(url1)
expect(
verifyLocalGetUrlSignature(
'my-bucket',
'dir/sleep.png',
parsed1.searchParams.get('Signature'),
parsed1.searchParams.get('Expires'),
),
).toBe(true)
// Simulate 15 hours of host sleep: wall clock advances past the 12h expiry while performance.now() pauses
wallNow += 15 * 3600 * 1000
perfNow += 1_000
const url2 = await localS3.presign('my-bucket', 'dir/sleep.png', 'GET')
expect(url2).not.toBe(url1)
const parsed2 = new URL(url2)
expect(
verifyLocalGetUrlSignature(
'my-bucket',
'dir/sleep.png',
parsed2.searchParams.get('Signature'),
parsed2.searchParams.get('Expires'),
),
).toBe(true)
} finally {
dateNowSpy.mockRestore()
perfNowSpy.mockRestore()
}
})
it('should not cache download URLs', async () => {
const url1 = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true)
const url2 = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', true)
+3 -3
View File
@@ -674,9 +674,9 @@ export class S3StorageService implements S3Service {
)
: parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
const lifetimeSeconds = expiresInSeconds ?? defaultExpireHours * 3600
// With an explicit (usually short) lifetime, only reuse a cached URL while it has at
// least half of its lifetime left, so callers never receive a nearly expired link.
const cacheTtlMs = expiresInSeconds ? (lifetimeSeconds * 1000) / 2 : lifetimeSeconds * 1000
// Only reuse a cached URL while it has at least half of its lifetime left, so callers
// never receive a nearly expired link.
const cacheTtlMs = (lifetimeSeconds * 1000) / 2
const cacheKey = `${bucket}/${key}?download=${download || false}&filename=${filename || ''}&internal=${internal || false}&expires=${expiresInSeconds ?? 'default'}`
if (method === 'GET' && !download) {
@@ -15,6 +15,11 @@ test.describe('Uploader Resilience E2E Tests', () => {
test('keeps upload active on network drop and automatically resumes on reconnection', async ({
page,
}) => {
let isOffline = false
let markFirstSignStarted: () => void = () => {}
const firstSignStarted = new Promise<void>((resolve) => {
markFirstSignStarted = resolve
})
let releaseSign: () => void = () => {}
const signGate = new Promise<void>((resolve) => {
releaseSign = resolve
@@ -24,32 +29,46 @@ test.describe('Uploader Resilience E2E Tests', () => {
await page.route('**/api/teams/**/upload/sign', async (route) => {
signCalls++
if (signCalls === 1) {
// Wait until offline event is dispatched before releasing first sign call
markFirstSignStarted()
// Wait until the browser is offline before failing the in-flight sign request
await signGate
}
route.fulfill({
if (isOffline) {
// Playwright route.fulfill() bypasses context.setOffline(true) in Chromium,
// so explicitly abort mocked requests while offline to simulate a real network drop.
await route.abort('internetdisconnected').catch(() => {})
return
}
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ url: 'http://localhost:5199/mock-upload' }),
})
})
await page.route('**/mock-upload', (route) =>
route.fulfill({
await page.route('**/mock-upload', async (route) => {
if (isOffline) {
await route.abort('internetdisconnected').catch(() => {})
return
}
await route.fulfill({
status: 200,
headers: { ['ETag']: '"test-etag"' },
}),
)
})
})
await page.goto('/?view=uploader')
await expect(page.getByTestId('upload-status')).toHaveText('idle')
// Start upload
// Start upload and wait until the first sign request is in flight
await page.getByTestId('start-upload-btn').click()
await expect(page.getByTestId('upload-status')).toHaveText('uploading')
await firstSignStarted
// Simulate cutting the connection
isOffline = true
await page.context().setOffline(true)
await expect.poll(() => page.evaluate(() => navigator.onLine)).toBe(false)
releaseSign()
// Status remains 'uploading' during offline state and no error toast appears
@@ -58,10 +77,12 @@ test.describe('Uploader Resilience E2E Tests', () => {
await expect(page.locator('[data-sonner-toast][data-type="error"]')).toHaveCount(0)
// Reconnect network
isOffline = false
await page.context().setOffline(false)
// Upload automatically resumes and completes
await expect(page.getByTestId('upload-status')).toHaveText('completed', { timeout: 15_000 })
expect(signCalls).toBeGreaterThanOrEqual(2)
await expect(page.locator('[data-sonner-toast][data-type="error"]')).toHaveCount(0)
})