Traces: Consistent span colors for service names (#50782)

* Show consistent span colors

* Update tests

* Test for ensuring red is not used
This commit is contained in:
Joey Tawadrous 2022-06-16 08:24:19 +01:00 committed by GitHub
parent bd6c027a01
commit 7b14cd5fdb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 19 deletions

View File

@ -30,20 +30,10 @@ it('gives different colors for each for each key', () => {
expect(colorOne).not.toBe(colorTwo);
});
it('should clear cache', () => {
clear();
const colorOne = getColorByKey('serviceA', createTheme());
clear();
const colorTwo = getColorByKey('serviceB', createTheme());
expect(colorOne).toBe(colorTwo);
});
it('should not allow red', () => {
clear();
getColorByKey('serviceA', createTheme());
getColorByKey('serviceB', createTheme());
getColorByKey('serviceC', createTheme());
getColorByKey('serviceD', createTheme());
const colorFive = getColorByKey('serviceE', createTheme());
expect(colorFive).not.toBe('#E24D42');
// when aPAKNMeFcF is hashed it's index is 4
// which is red, which we disallow because it looks like an error
const colorOne = getColorByKey('aPAKNMeFcF', createTheme());
expect(colorOne).not.toBe('#E24D42');
});

View File

@ -32,26 +32,36 @@ class ColorGenerator {
colorsHex: string[];
colorsRgb: Array<[number, number, number]>;
cache: Map<string, number>;
currentIdx: number;
constructor(colorsHex: string[]) {
this.colorsHex = colorsHex;
this.colorsRgb = colorsHex.map(strToRgb);
this.cache = new Map();
this.currentIdx = 0;
}
_getColorIndex(key: string): number {
let i = this.cache.get(key);
if (i == null) {
const hash = this.hashCode(key.toLowerCase());
const hashIndex = Math.abs(hash % this.colorsHex.length);
// colors[4] is red (which we want to disallow as a span color because it looks like an error)
i = this.currentIdx !== 4 ? this.currentIdx : this.currentIdx + 1;
i = hashIndex === 4 ? hashIndex + 1 : hashIndex;
this.cache.set(key, i);
this.currentIdx = (i + 1) % this.colorsHex.length;
}
return i;
}
hashCode(key: string) {
var hash = 0,
i,
chr;
for (i = 0; i < key.length; i++) {
chr = key.charCodeAt(i);
hash = (hash << 5) - hash + chr;
}
return hash;
}
/**
* Will assign a color to an arbitrary key.
* If the key has been used already, it will
@ -74,7 +84,6 @@ class ColorGenerator {
clear() {
this.cache.clear();
this.currentIdx = 0;
}
}