corebrum
v0.1.0
Published
Execute JavaScript code transparently on Corebrum's distributed compute infrastructure
Maintainers
Readme
Corebrum JavaScript Library
Execute JavaScript code transparently on Corebrum's distributed compute infrastructure with minimal code changes.
Installation
Install Corebrum using npm:
npm install corebrumQuick Start
Using the Wrapper Pattern
Wrap your functions to execute them on Corebrum:
const corebrum = require('corebrum');
// Configure Corebrum connection (optional, defaults to http://localhost:6502)
corebrum.configure({
baseUrl: 'http://localhost:6502',
identityId: 'your-identity-id' // Optional
});
// Wrap function to run on Corebrum
const processData = corebrum.run((data) => {
// Your processing code here
const result = data.map(item => ({
...item,
processed: true,
timestamp: Date.now()
}));
return result;
});
// Call normally - executes on Corebrum
const result = await processData([
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]);
console.log(result);Using the Execute Method
Execute raw JavaScript code directly:
const corebrum = require('corebrum');
// Execute code with inputs
const result = await corebrum.execute(`
function calculate() {
return Math.sqrt(144);
}
const result = calculate(); // Assign to result variable
`, {}, { name: 'calculate_task' });
console.log(result); // 12With Input Data
const processWithInputs = corebrum.run((datasetUrl, epochs = 10) => {
// Your processing code here
return {
accuracy: 0.95,
loss: 0.05,
epochs: epochs
};
});
const result = await processWithInputs('https://example.com/data.csv', 20);Features
- Transparent Execution: Code runs as if it were local, but executes on Corebrum's distributed infrastructure
- Automatic Dependency Detection: Automatically detects and includes npm package dependencies from
require()andimportstatements - Input/Output Serialization: Handles JSON-serializable inputs and outputs automatically
- Error Handling: Corebrum errors surface naturally as JavaScript exceptions
- Identity Support: Works with Corebrum's identity and memory system
- Timeout Control: Configurable task timeouts
- Progress Tracking: Real-time status updates via Server-Sent Events (SSE)
API Reference
Corebrum Class
Main client class for interacting with Corebrum.
const { Corebrum } = require('corebrum');
const client = new Corebrum({
baseUrl: 'http://localhost:6502', // Corebrum web server URL
identityId: null, // Optional identity ID
timeout: 300, // Task timeout in seconds
pollInterval: 2.0, // Polling interval in seconds
maxPollAttempts: 300 // Maximum polling attempts
});run(func, options)
Wraps a function to execute it on Corebrum.
Parameters:
func(Function): The function to wrapoptions(Object, optional): Additional optionsname(string): Task name (default: function name or 'anonymous_function')timeout(number): Task timeout in secondsidentityId(string): Identity ID for memory contextdependencies(Array): Explicit list of npm package dependencies
Returns: (Function) Wrapped async function that executes on Corebrum
Example:
const add = corebrum.run((a, b) => a + b);
const result = await add(5, 3); // Executes on Corebrumexecute(code, inputData, options)
Execute raw JavaScript code directly.
Parameters:
code(string): JavaScript code to executeinputData(Object): Input data for the code (default: {})options(Object, optional): Additional optionsname(string): Task name (default: 'execute_task')timeout(number): Task timeout in secondsidentityId(string): Identity ID for memory contextdependencies(Array): Explicit list of npm package dependencies
Returns: (Promise) Execution result
Example:
const result = await corebrum.execute(`
const result = Math.sqrt(144);
`, {}, { name: 'sqrt_task' });configure(options)
Configure the global Corebrum instance.
Parameters:
options(Object): Configuration options (same as Corebrum constructor)
Example:
corebrum.configure({
baseUrl: 'http://localhost:6502',
identityId: 'my-identity',
timeout: 600
});Comparison: run() vs execute()
| Feature | run() | execute() |
|---------|---------|-------------|
| Best For | Existing functions | Raw code strings |
| Code Format | Function object | String |
| Input Handling | Function parameters | inputData object |
| Result Capture | Return value | Must assign to result variable |
| Use Case | Wrapping existing code | Dynamic code execution |
When to Use run()
- You have a function already defined
- You want to execute existing code with minimal changes
- You prefer a decorator-like pattern
const processData = corebrum.run((data) => {
return data.map(x => x * 2);
});
const result = await processData([1, 2, 3]);When to Use execute()
- You have code as a string
- You want to execute code dynamically
- You're building code programmatically
const code = `
const result = numbers.reduce((a, b) => a + b, 0);
`;
const result = await corebrum.execute(code, { numbers: [1, 2, 3] });Example Scripts
This directory contains example scripts demonstrating how to use the Corebrum JavaScript library.
basic_usage.js
Basic examples showing:
- Simple function execution
- Data processing
- Mathematical computations
- Using the
execute()method
Run:
node examples/basic_usage.jsadvanced_usage.js
Advanced examples showing:
- Functions with default arguments
- Error handling
- Custom timeouts
- Identity context
- Execute with inputs
Run:
node examples/advanced_usage.jsfactorial_demo.js
Factorial calculation demo that demonstrates three different ways to calculate factorials using Corebrum:
- Using the
corebrum.run()wrapper - Using
corebrum.execute()method - Recursive factorial implementation
- Parallel execution of multiple factorials
Run:
node examples/factorial_demo.jsError Handling
Corebrum errors are thrown as JavaScript exceptions:
const { TaskSubmissionError, TaskExecutionError, TaskTimeoutError } = require('corebrum');
try {
const result = await myFunction();
} catch (error) {
if (error instanceof TaskSubmissionError) {
console.error('Failed to submit task:', error.message);
} else if (error instanceof TaskExecutionError) {
console.error('Task execution failed:', error.message);
} else if (error instanceof TaskTimeoutError) {
console.error('Task timed out:', error.message);
} else {
console.error('Unknown error:', error.message);
}
}Dependency Detection
The library automatically detects npm package dependencies from your code:
// This will automatically detect 'lodash' as a dependency
const processData = corebrum.run((data) => {
const _ = require('lodash');
return _.map(data, x => x * 2);
});You can also explicitly specify dependencies:
const processData = corebrum.run((data) => {
// Your code
}, {
dependencies: ['lodash', 'axios']
});Configuration
Environment Variables
COREBRUM_DEBUG: Set to'true'to enable debug logging
Default Configuration
{
baseUrl: 'http://localhost:6502',
identityId: null,
timeout: 300, // 5 minutes
pollInterval: 2.0, // 2 seconds
maxPollAttempts: 300 // 10 minutes max
}Requirements
- Node.js >= 12.0.0
- Corebrum server running and accessible
License
MIT
Contributing
Contributions are welcome! Please see the contributing guidelines.
Links
- GitHub Repository: https://github.com/Corebrum/corebrum-npm
- Corebrum Platform: https://github.com/corebrum/corebrum
- Corebrum Examples: https://github.com/Corebrum/corebrum-examples
