-
Notifications
You must be signed in to change notification settings - Fork 157
feat(logger): add circular buffer #3593
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
dreamorosi
merged 7 commits into
aws-powertools:main
from
VatsalGoel3:feature/log-buffering
Feb 13, 2025
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
4a49b6c
feat(logger): add log buffering module (SizedItem, SizedSet, Circular…
VatsalGoel3 ac9b16a
feat(logger): add log buffering module with unit tests
VatsalGoel3 56786d5
Merge branch 'main' into feature/log-buffering
VatsalGoel3 80f83cd
Merge branch 'main' into feature/log-buffering
dreamorosi ee61392
fix(logger): enforce string values in SizedItem and improve buffer ov…
VatsalGoel3 bb813a6
fix(logger): remove unnecessary instantiation in SizedItem test
VatsalGoel3 e17b3fd
chore: reliability items
dreamorosi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
import { isString } from '@aws-lambda-powertools/commons/typeutils'; | ||
|
||
export class SizedItem<V> { | ||
public value: V; | ||
public logLevel: number; | ||
public byteSize: number; | ||
|
||
constructor(value: V, logLevel: number) { | ||
if (!isString(value)) { | ||
throw new Error('Value should be a string'); | ||
} | ||
this.value = value; | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
this.logLevel = logLevel; | ||
this.byteSize = Buffer.byteLength(value as unknown as string); | ||
} | ||
} | ||
|
||
export class SizedSet<V> extends Set<SizedItem<V>> { | ||
public currentBytesSize = 0; | ||
|
||
add(item: SizedItem<V>): this { | ||
this.currentBytesSize += item.byteSize; | ||
super.add(item); | ||
return this; | ||
} | ||
|
||
delete(item: SizedItem<V>): boolean { | ||
const wasDeleted = super.delete(item); | ||
if (wasDeleted) { | ||
this.currentBytesSize -= item.byteSize; | ||
} | ||
return wasDeleted; | ||
} | ||
|
||
clear(): void { | ||
super.clear(); | ||
this.currentBytesSize = 0; | ||
} | ||
|
||
shift(): SizedItem<V> | undefined { | ||
const firstElement = this.values().next().value; | ||
if (firstElement) { | ||
this.delete(firstElement); | ||
} | ||
return firstElement; | ||
} | ||
} | ||
|
||
export class CircularMap<V> extends Map<string, SizedSet<V>> { | ||
readonly #maxBytesSize: number; | ||
readonly #onBufferOverflow?: () => void; | ||
|
||
constructor({ | ||
maxBytesSize, | ||
onBufferOverflow, | ||
}: { | ||
maxBytesSize: number; | ||
onBufferOverflow?: () => void; | ||
}) { | ||
super(); | ||
this.#maxBytesSize = maxBytesSize; | ||
this.#onBufferOverflow = onBufferOverflow; | ||
} | ||
|
||
setItem(key: string, value: V, logLevel: number): this { | ||
const item = new SizedItem<V>(value, logLevel); | ||
|
||
if (item.byteSize > this.#maxBytesSize) { | ||
throw new Error('Item too big'); | ||
} | ||
|
||
const buffer = this.get(key) || new SizedSet<V>(); | ||
|
||
if (buffer.currentBytesSize + item.byteSize >= this.#maxBytesSize) { | ||
this.#deleteFromBufferUntilSizeIsLessThanMax(buffer, item); | ||
if (this.#onBufferOverflow) { | ||
this.#onBufferOverflow(); | ||
} | ||
} | ||
|
||
buffer.add(item); | ||
super.set(key, buffer); | ||
return this; | ||
} | ||
|
||
readonly #deleteFromBufferUntilSizeIsLessThanMax = ( | ||
buffer: SizedSet<V>, | ||
item: SizedItem<V> | ||
) => { | ||
while (buffer.currentBytesSize + item.byteSize >= this.#maxBytesSize) { | ||
buffer.shift(); | ||
} | ||
}; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,146 @@ | ||
import { describe, expect, it, vi } from 'vitest'; | ||
import { CircularMap, SizedItem, SizedSet } from '../../src/logBuffer.js'; | ||
|
||
describe('SizedItem', () => { | ||
it('calculates the byteSize based on string value', () => { | ||
// Prepare | ||
const logEntry = 'hello world'; | ||
|
||
// Act | ||
const item = new SizedItem(logEntry, 1); | ||
|
||
// Assess | ||
const expectedByteSize = Buffer.byteLength(logEntry); | ||
expect(item.byteSize).toBe(expectedByteSize); | ||
}); | ||
|
||
it('throws an error if value is not a string', () => { | ||
// Prepare | ||
const invalidValue = { message: 'not a string' }; | ||
|
||
// Act & Assess | ||
expect( | ||
() => new SizedItem(invalidValue as unknown as string, 1) | ||
).toThrowError('Value should be a string'); | ||
}); | ||
}); | ||
|
||
describe('SizedSet', () => { | ||
it('adds an item and updates currentBytesSize correctly', () => { | ||
// Prepare | ||
const set = new SizedSet<string>(); | ||
const item = new SizedItem('value', 1); | ||
|
||
// Act | ||
set.add(item); | ||
|
||
// Assess | ||
expect(set.currentBytesSize).toBe(item.byteSize); | ||
expect(set.has(item)).toBe(true); | ||
}); | ||
|
||
it('deletes an item and updates currentBytesSize correctly', () => { | ||
// Prepare | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const set = new SizedSet<string>(); | ||
const item = new SizedItem('value', 1); | ||
set.add(item); | ||
const initialSize = set.currentBytesSize; | ||
|
||
// Act | ||
const result = set.delete(item); | ||
|
||
// Assess | ||
expect(result).toBe(true); | ||
expect(set.currentBytesSize).toBe(initialSize - item.byteSize); | ||
expect(set.has(item)).toBe(false); | ||
}); | ||
|
||
it('clears all items and resets currentBytesSize to 0', () => { | ||
// Prepare | ||
const set = new SizedSet<string>(); | ||
set.add(new SizedItem('b', 1)); | ||
set.add(new SizedItem('d', 1)); | ||
|
||
// Act | ||
set.clear(); | ||
|
||
// Assess | ||
expect(set.currentBytesSize).toBe(0); | ||
expect(set.size).toBe(0); | ||
}); | ||
|
||
it('removes the first inserted item with shift', () => { | ||
// Prepare | ||
const set = new SizedSet<string>(); | ||
const item1 = new SizedItem('first', 1); | ||
const item2 = new SizedItem('second', 1); | ||
set.add(item1); | ||
set.add(item2); | ||
|
||
// Act | ||
const shiftedItem = set.shift(); | ||
|
||
// Assess | ||
expect(shiftedItem).toEqual(item1); | ||
expect(set.has(item1)).toBe(false); | ||
expect(set.currentBytesSize).toBe(item2.byteSize); | ||
}); | ||
}); | ||
|
||
describe('CircularMap', () => { | ||
it('adds items to a new buffer for a given key', () => { | ||
// Prepare | ||
const maxBytes = 200; | ||
const circularMap = new CircularMap<string>({ | ||
maxBytesSize: maxBytes, | ||
}); | ||
|
||
// Act | ||
circularMap.setItem('trace-1', 'first log', 1); | ||
|
||
// Assess | ||
const buffer = circularMap.get('trace-1'); | ||
expect(buffer).toBeDefined(); | ||
if (buffer) { | ||
expect(buffer.currentBytesSize).toBeGreaterThan(0); | ||
expect(buffer.size).toBe(1); | ||
} | ||
}); | ||
|
||
it('throws an error when an item exceeds maxBytesSize', () => { | ||
// Prepare | ||
const maxBytes = 10; | ||
const circularMap = new CircularMap<string>({ | ||
maxBytesSize: maxBytes, | ||
}); | ||
|
||
// Act & Assess | ||
expect(() => { | ||
circularMap.setItem('trace-1', 'a very long message', 1); | ||
}).toThrowError('Item too big'); | ||
}); | ||
|
||
it('evicts items when the buffer overflows and call the overflow callback', () => { | ||
// Prepare | ||
const options = { | ||
maxBytesSize: 15, | ||
onBufferOverflow: vi.fn(), | ||
}; | ||
const circularMap = new CircularMap<string>(options); | ||
const smallEntry = '12345'; | ||
|
||
const entryByteSize = Buffer.byteLength(smallEntry); | ||
const entriesCount = Math.ceil(options.maxBytesSize / entryByteSize); | ||
|
||
// Act | ||
for (let i = 0; i < entriesCount; i++) { | ||
circularMap.setItem('trace-1', smallEntry, 1); | ||
} | ||
|
||
// Assess | ||
expect(options.onBufferOverflow).toHaveBeenCalledTimes(1); | ||
expect(circularMap.get('trace-1')?.currentBytesSize).toBeLessThan( | ||
options.maxBytesSize | ||
); | ||
}); | ||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.