Skip to content
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

chore: adds SLO retries metrics #304

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions src/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* Context object allows to pass a context-chain (number of contexts, linked by "parent" field) thru function calls stack.
*
* To do this, you need to call functions like "context.do(() => [some function])". And in this "some function" at the
* beginning execute "const context = getContext();".
*
* Create a new context - "new Context(context?)". If context is provided, then new context considers it as a child-context.
* Otherwise, it's new context with an id, if newId() function was specified.
*
* Getting the context fields "... = context...". Also, context might have methods.
*
* Specific part of context-chain can be obtained thru findContextByClass() method.
*/
export class Context {

readonly id?: any;
readonly parent?: Context;

constructor(parent?: Context) {
if (parent) {
if (parent.id) {
this.id = parent.id;
}
this.parent = parent;
} else {
const id = newId();
if (id) {
this.id = id;
}
}
}

do<T>(func: () => T): T {
const prevContext = _context;
try {
_context = this;
return func();
} finally {
_context = prevContext;
}
}

findContextByClass<T extends Context>(type: Function): T | null {
let ctx: Context | undefined = this;

while (ctx) {
if (ctx instanceof type) {
return ctx as T;
}
ctx = ctx.parent;
}

return null;
}

toString() {
return this.id ? `${this.id}: ` : '';
}
}

/**
* This is an object that does not contain any context, but allows to execute context.do().
*/
const NOT_A_CONTEXT = Object.create(Context.prototype);

/**
* The current context so that it can be retrieved via getConext().
*/
let _context: any = NOT_A_CONTEXT;

/**
* Method of generating a new id for a new context.
*/
let newId: () => any = () => undefined;

/**
* Sets the id generator. By default, the id remain undefined.
*/
export function setContextNewId(generateNewId: () => any) {
newId = generateNewId;
}

/**
* The context must be taken in the begining of a function before a first 'await'.
*
* Ex.: const context = getContext();
*/
export function getContext(): Context {
return _context;
}
Loading