-
Notifications
You must be signed in to change notification settings - Fork 2
Consensus helpers #12
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
Merged
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 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,36 @@ | ||
import { cre, type Environment } from "@cre/sdk/cre"; | ||
import { type HandlerEntry } from "@cre/sdk/workflow"; | ||
import type { ConfigHandlerParams } from "./utils/config"; | ||
|
||
/** | ||
* Abstract base class for all CRE workflows | ||
* Provides common functionality and patterns | ||
*/ | ||
export abstract class Workflow<TConfig = unknown> { | ||
constructor(private readonly configHandlerParams?: ConfigHandlerParams) {} | ||
|
||
/** | ||
* Override this method to define your workflow handlers | ||
*/ | ||
protected abstract initHandlers(env: Environment<TConfig>): HandlerEntry[]; | ||
|
||
/** | ||
* Main workflow initialization - called by the runner | ||
*/ | ||
public initWorkflow = (env: Environment<TConfig>) => { | ||
return this.initHandlers(env); | ||
}; | ||
|
||
/** | ||
* Creates and runs the workflow runner | ||
*/ | ||
public async run(): Promise<void> { | ||
try { | ||
const runner = await cre.newRunner<TConfig>(this.configHandlerParams); | ||
await runner.run(this.initWorkflow); | ||
} catch (error) { | ||
console.log("Workflow error:", JSON.stringify(error, null, 2)); | ||
throw error; | ||
} | ||
} | ||
} |
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,97 @@ | ||
import { cre } from "@cre/sdk/cre"; | ||
import { | ||
type ConsenusAggregator, | ||
getAggregatedValue, | ||
} from "@cre/sdk/utils/values/consensus"; | ||
import { type SupportedValueTypes, val } from "@cre/sdk/utils/values/value"; | ||
|
||
// ===== TYPE HELPERS FOR BETTER TYPE SAFETY ===== | ||
|
||
// Map value types to their expected input types | ||
type ValueTypeInput = { | ||
string: string; | ||
float64: number; | ||
int64: number | bigint | string; | ||
bigint: bigint; | ||
bool: boolean; | ||
bytes: Uint8Array | ArrayBuffer; | ||
time: Date | number | string; | ||
list: Array<unknown>; | ||
mapValue: Record<string, unknown>; | ||
decimal: string; | ||
from: unknown; | ||
}; | ||
|
||
// ===== CORE CONSENSUS WRAPPER ===== | ||
|
||
/** | ||
* Core consensus wrapper with strong typing | ||
* Ensures the function return type matches the value type input requirements | ||
*/ | ||
export const useConsensus = < | ||
TValueType extends keyof ValueTypeInput & SupportedValueTypes, | ||
TArgs extends readonly any[], | ||
TReturn extends ValueTypeInput[TValueType] | ||
>( | ||
fn: (...args: TArgs) => Promise<TReturn>, | ||
valueType: TValueType, | ||
aggregationType: ConsenusAggregator | ||
) => { | ||
return async (...args: TArgs): Promise<any> => { | ||
return cre.runInNodeMode(async () => { | ||
const result = await fn(...args); | ||
return getAggregatedValue( | ||
(val as any)[valueType](result), | ||
aggregationType | ||
); | ||
}); | ||
}; | ||
}; | ||
|
||
// ===== TYPED CONVENIENCE WRAPPERS ===== | ||
|
||
/** | ||
* Median consensus for numerical data | ||
* Automatically infers correct return type based on value type | ||
*/ | ||
export const useMedianConsensus = <TArgs extends readonly any[]>( | ||
fn: (...args: TArgs) => Promise<number>, | ||
valueType: "float64" | "int64" = "float64" | ||
) => useConsensus(fn, valueType, "median"); | ||
|
||
/** | ||
* Identical consensus - all nodes must agree exactly | ||
* Supports any value type with proper typing | ||
*/ | ||
export const useIdenticalConsensus = < | ||
TValueType extends keyof ValueTypeInput & SupportedValueTypes, | ||
TArgs extends readonly any[], | ||
TReturn extends ValueTypeInput[TValueType] | ||
>( | ||
fn: (...args: TArgs) => Promise<TReturn>, | ||
valueType: TValueType | ||
) => useConsensus(fn, valueType, "identical"); | ||
|
||
/** | ||
* Common prefix consensus for strings and bytes | ||
*/ | ||
export const useCommonPrefixConsensus = < | ||
TValueType extends ("string" | "bytes") & keyof ValueTypeInput, | ||
TArgs extends readonly any[], | ||
TReturn extends ValueTypeInput[TValueType] | ||
>( | ||
fn: (...args: TArgs) => Promise<TReturn>, | ||
valueType: TValueType | ||
) => useConsensus(fn, valueType, "commonPrefix"); | ||
|
||
/** | ||
* Common suffix consensus for strings and bytes | ||
*/ | ||
export const useCommonSuffixConsensus = < | ||
TValueType extends ("string" | "bytes") & keyof ValueTypeInput, | ||
TArgs extends readonly any[], | ||
TReturn extends ValueTypeInput[TValueType] | ||
>( | ||
fn: (...args: TArgs) => Promise<TReturn>, | ||
valueType: TValueType | ||
) => useConsensus(fn, valueType, "commonSuffix"); |
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
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
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,53 @@ | ||
import { z } from "zod"; | ||
import { cre, type Environment } from "@cre/sdk/cre"; | ||
import { useMedianConsensus } from "@cre/sdk/utils/values/consensus-hooks"; | ||
|
||
// Config struct defines the parameters that can be passed to the workflow | ||
const configSchema = z.object({ | ||
schedule: z.string(), | ||
apiUrl: z.string(), | ||
}); | ||
|
||
type Config = z.infer<typeof configSchema>; | ||
|
||
// Wrap with consensus logic using function call | ||
const fetchMathResult = useMedianConsensus(async (config: Config) => { | ||
const response = await cre.utils.fetch({ | ||
url: config.apiUrl, | ||
}); | ||
return Number.parseFloat(response.body.trim()); | ||
}, "float64"); | ||
|
||
// This is your handler which will perform the desired action | ||
const onCronTrigger = async (env: Environment<Config>) => { | ||
const aggregatedValue = await fetchMathResult(env.config); | ||
cre.sendResponseValue(cre.utils.val.mapValue({ Result: aggregatedValue })); | ||
}; | ||
|
||
// InitWorkflow is the required entry point for a CRE workflow | ||
// The runner calls this function to initialize the workflow and register its handlers | ||
const initWorkflow = (env: Environment<Config>) => { | ||
const cron = new cre.capabilities.CronCapability(); | ||
|
||
return [ | ||
cre.handler( | ||
// Use the schedule from our config file | ||
cron.trigger({ schedule: env.config?.schedule }), | ||
onCronTrigger | ||
), | ||
]; | ||
}; | ||
|
||
// main is the entry point for the workflow | ||
export async function main() { | ||
try { | ||
const runner = await cre.newRunner<Config>({ | ||
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. I think workflows are starting to look a lot better and really take shape. |
||
configSchema, | ||
}); | ||
await runner.run(initWorkflow); | ||
} catch (error) { | ||
console.log("error", JSON.stringify(error, null, 2)); | ||
} | ||
} | ||
|
||
main(); |
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
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.
Do these exist as generated constants from the protos?
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.
Protos exposes these as ENUM with numeric values which is not perfect :S but yeah it's called
AggregationType
I believe.