feat: Complete 6 additional SDK implementations with fixes and examples

Go Async SDK (clients/go/async/):
- Fixed case-sensitive language detection bug (.R for R language)
- Created go.mod for module management
- Added comprehensive test suite
- Created 3 examples with expected output comments
- Added README with full documentation

Java Sync SDK (clients/java/sync/):
- RENAMED: Unsandbox.java -> Un.java (matches naming convention)
- Updated class name from Unsandbox to Un
- Created pom.xml for Maven build
- Added 6 examples (simple + SDK client versions)
- Created test suite with JUnit 5
- Added README with API documentation

JavaScript Async SDK (clients/javascript/async/):
- Fixed unused import
- Created package.json with ES module support
- Added 5 examples covering all async patterns
- Created 71 tests (all passing)
- Added comprehensive README

PHP Sync SDK (clients/php/sync/):
- RENAMED: Unsandbox.php -> un.php (matches naming convention)
- Created composer.json with PSR-4 autoloading
- Created phpunit.xml for testing
- Added 4 examples with expected output comments
- Created 54 tests across 4 test files
- Added README with full documentation

Ruby Sync SDK (clients/ruby/sync/):
- Created Gemfile and un.gemspec
- Created Rakefile with test task
- Updated examples to actually use the SDK
- Added 4 examples (hello_world, async_job, language_detection, snapshots)
- Created comprehensive test suite with 30+ tests
- Added README with documentation

Rust Sync SDK (clients/rust/sync/):
- Updated Cargo.toml with example declarations
- Created 4 examples (hello_world, fibonacci, multi_language, async_polling)
- Added comprehensive README with API reference
- All dependencies verified correct

All SDKs verified:
- HMAC-SHA256 authentication implemented
- 4-tier credential system (args > env > ~/.unsandbox > ./accounts.csv)
- Expected output comments for pipeline validation
- Proper error handling
- Language detection support
This commit is contained in:
russell@unturf.com 2026-01-15 17:32:24 -05:00
parent 1e4fe2ef96
commit 331cba42aa
66 changed files with 18743 additions and 4 deletions

View file

@ -0,0 +1,79 @@
#!/usr/bin/env node
/**
* Async Job Polling example for unsandbox JavaScript SDK
*
* Demonstrates fire-and-forget execution with manual job polling.
* Shows how to start an async job and poll for its completion.
*
* To run:
* export UNSANDBOX_PUBLIC_KEY="your-public-key"
* export UNSANDBOX_SECRET_KEY="your-secret-key"
* node async_job_polling.js
*
* Expected output:
* Starting async job...
* Job ID: job_abc123
* Polling for completion...
* Poll 1: status = running
* Poll 2: status = completed
* Final result: 42
*/
import {
executeAsync,
getJob,
waitForJob,
CredentialsError,
} from '../src/un_async.js';
async function main() {
try {
// Long-running code to execute
const code = `
import time
time.sleep(0.5) # Simulate some work
print(42)
`;
console.log('Starting async job...');
// Start the job (returns immediately with job_id)
const jobId = await executeAsync('python', code);
console.log(`Job ID: ${jobId}`);
// Option 1: Manual polling
console.log('Polling for completion...');
let pollCount = 0;
let result;
while (true) {
pollCount++;
result = await getJob(jobId);
console.log(`Poll ${pollCount}: status = ${result.status}`);
if (['completed', 'failed', 'timeout', 'cancelled'].includes(result.status)) {
break;
}
// Wait before next poll
await new Promise((resolve) => setTimeout(resolve, 300));
}
console.log(`Final result: ${(result.stdout || '').trim()}`);
return result.status === 'completed' ? 0 : 1;
// Option 2: Use waitForJob (recommended - handles polling automatically)
// const result = await waitForJob(jobId);
// console.log(`Result: ${result.stdout}`);
} catch (e) {
if (e instanceof CredentialsError) {
console.log(`Credentials error: ${e.message}`);
} else {
console.log(`Error: ${e.message}`);
console.error(e);
}
return 1;
}
}
main().then(process.exit);

View file

@ -0,0 +1,76 @@
#!/usr/bin/env node
/**
* Concurrent Execution example for unsandbox JavaScript SDK
*
* Demonstrates running code in multiple languages concurrently.
* Shows the power of async/await with Promise.all() for parallel execution.
*
* To run:
* export UNSANDBOX_PUBLIC_KEY="your-public-key"
* export UNSANDBOX_SECRET_KEY="your-secret-key"
* node concurrent_execution.js
*
* Expected output:
* Starting concurrent execution in 4 languages...
* [python] Output: Hello from Python!
* [javascript] Output: Hello from JavaScript!
* [go] Output: Hello from Go!
* [ruby] Output: Hello from Ruby!
* All executions completed in Xms
*/
import { executeCode, CredentialsError } from '../src/un_async.js';
const LANGUAGE_CODE = {
python: 'print("Hello from Python!")',
javascript: 'console.log("Hello from JavaScript!");',
go: `package main
import "fmt"
func main() {
fmt.Println("Hello from Go!")
}`,
ruby: 'puts "Hello from Ruby!"',
};
async function runCode(language, code) {
try {
const result = await executeCode(language, code);
const output = (result.stdout || '').trim();
console.log(`[${language}] Output: ${output}`);
return { language, output, success: true };
} catch (e) {
console.log(`[${language}] Error: ${e.message}`);
return { language, error: e.message, success: false };
}
}
async function main() {
try {
console.log('Starting concurrent execution in 4 languages...');
const startTime = Date.now();
// Execute all languages concurrently
const results = await Promise.all(
Object.entries(LANGUAGE_CODE).map(([lang, code]) => runCode(lang, code))
);
const elapsed = Date.now() - startTime;
console.log(`All executions completed in ${elapsed}ms`);
// Check for errors
const successCount = results.filter((r) => r.success).length;
console.log(`Success: ${successCount}/${results.length}`);
return successCount === results.length ? 0 : 1;
} catch (e) {
if (e instanceof CredentialsError) {
console.log(`Credentials error: ${e.message}`);
} else {
console.log(`Error: ${e.message}`);
console.error(e);
}
return 1;
}
}
main().then(process.exit);

View file

@ -0,0 +1,71 @@
#!/usr/bin/env node
/**
* Fibonacci example for unsandbox JavaScript SDK - Asynchronous Version
*
* Demonstrates concurrent fibonacci calculations using async/await.
* Shows how to run multiple concurrent operations with Promise.all().
*
* To run:
* export UNSANDBOX_PUBLIC_KEY="your-public-key"
* export UNSANDBOX_SECRET_KEY="your-secret-key"
* node fibonacci.js
*
* Expected output:
* Starting 3 concurrent fibonacci calculations...
* [fib-10] Result: fib(10) = 55
* [fib-15] Result: fib(15) = 610
* [fib-12] Result: fib(12) = 144
* All calculations completed!
*/
import { executeCode, CredentialsError } from '../src/un_async.js';
async function runFibonacci(n, label) {
const code = `
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
print(f"fib(${n}) = {fib(${n})}")
`;
try {
const result = await executeCode('python', code);
const output = (result.stdout || '').trim();
console.log(`[${label}] Result: ${output}`);
return { label, output };
} catch (e) {
console.log(`[${label}] Error: ${e.message}`);
return { label, error: e.message };
}
}
async function main() {
try {
console.log('Starting 3 concurrent fibonacci calculations...');
// Run all fibonacci calculations concurrently
const results = await Promise.all([
runFibonacci(10, 'fib-10'),
runFibonacci(15, 'fib-15'),
runFibonacci(12, 'fib-12'),
]);
console.log('All calculations completed!');
// Check for errors
const hasErrors = results.some((r) => r.error);
return hasErrors ? 1 : 0;
} catch (e) {
if (e instanceof CredentialsError) {
console.log(`Credentials error: ${e.message}`);
} else {
console.log(`Error: ${e.message}`);
console.error(e);
}
return 1;
}
}
main().then(process.exit);

View file

@ -0,0 +1,52 @@
#!/usr/bin/env node
/**
* Hello World example for unsandbox JavaScript SDK - Asynchronous Version
*
* This example demonstrates basic async execution with the unsandbox SDK.
* Shows how to use async/await with the SDK for simple code execution.
*
* To run:
* export UNSANDBOX_PUBLIC_KEY="your-public-key"
* export UNSANDBOX_SECRET_KEY="your-secret-key"
* node hello_world.js
*
* Expected output:
* Executing code asynchronously...
* Result status: completed
* Output: Hello from async unsandbox!
*/
import { executeCode, CredentialsError } from '../src/un_async.js';
async function main() {
// The code to execute
const code = 'print("Hello from async unsandbox!")';
try {
console.log('Executing code asynchronously...');
const result = await executeCode('python', code);
if (result.status === 'completed') {
console.log(`Result status: ${result.status}`);
console.log(`Output: ${(result.stdout || '').trim()}`);
if (result.stderr) {
console.log(`Errors: ${result.stderr}`);
}
return 0;
} else {
console.log(`Execution failed with status: ${result.status}`);
console.log(`Error: ${result.error || 'Unknown error'}`);
return 1;
}
} catch (e) {
if (e instanceof CredentialsError) {
console.log(`Credentials error: ${e.message}`);
} else {
console.log(`Error: ${e.message}`);
console.error(e);
}
return 1;
}
}
main().then(process.exit);

View file

@ -0,0 +1,49 @@
#!/usr/bin/env node
/**
* Language Detection example for unsandbox JavaScript SDK
*
* Demonstrates automatic language detection from filenames.
* This is a purely local operation that doesn't require API credentials.
*
* To run:
* node language_detection.js
*
* Expected output:
* Testing language detection from filenames...
* script.py -> python
* app.js -> javascript
* main.go -> go
* Cargo.rs -> rust
* Main.java -> java
* test.rb -> ruby
* index.ts -> typescript
* unknown -> null
* Language detection complete!
*/
import { detectLanguage } from '../src/un_async.js';
const TEST_FILES = [
'script.py',
'app.js',
'main.go',
'Cargo.rs',
'Main.java',
'test.rb',
'index.ts',
'unknown',
];
function main() {
console.log('Testing language detection from filenames...');
for (const filename of TEST_FILES) {
const language = detectLanguage(filename);
console.log(`${filename} -> ${language}`);
}
console.log('Language detection complete!');
return 0;
}
process.exit(main());