-
Notifications
You must be signed in to change notification settings - Fork 13
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
feat: add compensation feature to deno context and utils #945
Open
j03-dev
wants to merge
1
commit into
main
Choose a base branch
from
feat/met-712-sub-context-compensate
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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 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
This file contains 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 |
---|---|---|
|
@@ -318,7 +318,12 @@ export type OperationEvent = | |
| { type: "Send"; event_name: string; value: unknown } | ||
| { type: "Stop"; result: unknown } | ||
| { type: "Start"; kwargs: Record<string, unknown> } | ||
| { type: "Compensate" }; | ||
| { | ||
type: "Compensate"; | ||
save_id: number; | ||
error: string; | ||
compensation_result: any; | ||
}; | ||
Comment on lines
+321
to
+326
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Underlying protobuff type is not generated and converted. |
||
|
||
export type Operation = { at: string; event: OperationEvent }; | ||
|
||
|
This file contains 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 |
---|---|---|
|
@@ -4,6 +4,7 @@ | |
import { make_internal } from "../../worker_utils.ts"; | ||
import { TaskContext } from "../deno/shared_types.ts"; | ||
import { appendIfOngoing, Interrupt, OperationEvent, Run } from "./types.ts"; | ||
import { randomUUID } from "../../crypto.ts"; | ||
|
||
// const isTest = Deno.env.get("DENO_TESTING") === "true"; | ||
const testBaseUrl = Deno.env.get("TEST_OVERRIDE_GQL_ORIGIN"); | ||
|
@@ -15,11 +16,14 @@ export class Context { | |
public kwargs = {}; | ||
gql: ReturnType<typeof createGQLClient>; | ||
logger: SubLogger; | ||
utils: Utils; | ||
compensationStack: (() => any | Promise<any>)[] = []; | ||
|
||
constructor(private run: Run, private internal: TaskContext) { | ||
this.gql = createGQLClient(internal); | ||
this.kwargs = getKwargsCopy(run); | ||
this.logger = new SubLogger(this); | ||
this.utils = new Utils(this); | ||
} | ||
|
||
#nextId() { | ||
|
@@ -33,7 +37,14 @@ export class Context { | |
appendIfOngoing(this.run, { at: new Date().toJSON(), event: op }); | ||
} | ||
|
||
async save<T>(fn: () => T | Promise<T>, option?: SaveOption) { | ||
async save<T>( | ||
fn: () => T | Promise<T>, | ||
option?: SaveOption, | ||
compensateWith?: () => T | Promise<T>, | ||
) { | ||
if (compensateWith) { | ||
this.compensationStack.push(compensateWith!); | ||
} | ||
const id = this.#nextId(); | ||
|
||
let currRetryCount = 1; | ||
|
@@ -76,6 +87,10 @@ export class Context { | |
|
||
return clonedResult; | ||
} catch (err: any) { | ||
if (option?.retry?.compensationOnfristFail) { | ||
await this.#triggerCompensation(id, err); | ||
throw err; | ||
} | ||
Comment on lines
89
to
+93
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💯 |
||
if ( | ||
option?.retry?.maxRetries && | ||
currRetryCount < option.retry.maxRetries | ||
|
@@ -103,6 +118,7 @@ export class Context { | |
|
||
throw Interrupt.Variant("SAVE_RETRY"); | ||
} else { | ||
await this.#triggerCompensation(id, err); | ||
this.#appendOp({ | ||
type: "Save", | ||
id, | ||
|
@@ -120,6 +136,23 @@ export class Context { | |
} | ||
} | ||
|
||
async #triggerCompensation(save_id: number, error: string) { | ||
const compensationStack = this.compensationStack; | ||
if (compensationStack && compensationStack.length) { | ||
compensationStack.reverse(); | ||
for (const compensationFn of compensationStack) { | ||
const result = await Promise.resolve(compensationFn()); | ||
const clonedResult = deepClone(result ?? null); | ||
this.#appendOp({ | ||
type: "Compensate", | ||
save_id, | ||
error, | ||
compensation_result: clonedResult, | ||
}); | ||
} | ||
} | ||
} | ||
|
||
sleep(durationMs: number) { | ||
const id = this.#nextId(); | ||
for (const { event } of this.run.operations) { | ||
|
@@ -350,6 +383,7 @@ interface SaveOption { | |
minBackoffMs: number; | ||
maxBackoffMs: number; | ||
maxRetries: number; | ||
compensationOnfristFail: boolean; | ||
}; | ||
} | ||
|
||
|
@@ -416,20 +450,19 @@ class RetryStrategy { | |
} | ||
} | ||
|
||
|
||
class SubLogger { | ||
constructor(private ctx: Context) {} | ||
|
||
async #log(kind: "warn" | "error" | "info", ...args: unknown[]) { | ||
await this.ctx.save(() => { | ||
const prefix = `[${kind.toUpperCase()}: ${this.ctx.getRun().run_id}]`; | ||
switch(kind) { | ||
switch (kind) { | ||
case "warn": { | ||
console.warn(prefix, ...args); | ||
break; | ||
} | ||
case "error": { | ||
console.error(prefix,...args); | ||
console.error(prefix, ...args); | ||
break; | ||
} | ||
default: { | ||
|
@@ -444,7 +477,7 @@ class SubLogger { | |
// Functions are omitted, | ||
// For example, JSON.stringify(() => 1234) => undefined (no throw) | ||
return json === undefined ? String(arg) : json; | ||
} catch(_) { | ||
} catch (_) { | ||
return String(arg); | ||
} | ||
}).join(" "); | ||
|
@@ -466,6 +499,24 @@ class SubLogger { | |
} | ||
} | ||
|
||
class Utils { | ||
constructor(private ctx: Context) {} | ||
|
||
async now() { | ||
return await this.ctx.save(() => Date.now()); | ||
} | ||
|
||
async random(a: number, b: number) { | ||
return await this.ctx.save(() => | ||
Math.floor(Math.random() * (b - a + 1)) + a | ||
); | ||
} | ||
|
||
async uuid4() { | ||
return await this.ctx.save(() => randomUUID()); | ||
} | ||
} | ||
|
||
function createGQLClient(internal: TaskContext) { | ||
const tgLocal = new URL(internal.meta.url); | ||
if (testBaseUrl) { | ||
|
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should be json string?