mirror of
https://github.com/hcengineering/platform.git
synced 2026-09-08 18:57:42 +02:00
+1








98652c6476
* Add bump-changes * Add utility tests * Add utility tests * Bump to new version of esbuild and typescript * v0.7.3 * use platform rig 0.7.10 * upgrade: memory engine optimized; change name to (was recommended by Copilot and Onnikov, TODO: CHANGE CLIENT TOO!!!) Signed-off-by: Leonid Kaganov <lleo@lleo.me> * Fix rate limits bug * Bump versions * Fix lock file * Fix bug in queue cleanup * Add more tests for queue * Add api-test tests * Initial commit * Improve hierarchy + tests Add tests for hierarchy and few performance/memory optimizations. * Add more hierarchy tests * Move from Huly platform repository * Add docker tests setup * Fix test to be executed only once * Add connection tests * Fix package include source files * More tests * Create README.md * Fix pnpm lock * Fix packages publish * Remove broken tests * feat: adjust hulylake client for storage adapter Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Fix export * Fix publish * Fix message update (#114) Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com> * Bump version Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com> * Bump versions Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Fix lang store (#115) Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com> * update hulylake client Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Bump version Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Add hulylake storage adapter Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Bump version Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * fix validation issues Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * fix: do not fail on deseralization error and add logs Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * bump version -> 0.1.14 Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * fix collaboration test Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Update prettier and new update-deps script Prettier + svelte support * fix unstable ydoc tests Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Add tx ordering middleware * Fix ordering tests * Fix Kafka close of admin * Add tests for measurement and understand overhead * Fix not updated lock file * Fix update-deps * Fix update-deps * Use latest platform-rig * Fix deps * Add rush check to CI * Use latest versions * Bump versions * Fix lock file * validate json patch Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * bump version -> 0.1.15 Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * fix merge unit tests Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Script to sync eslint deps * Fix deps * Fix tests * Fix platform-rig detection * Update to latest platform-rig * Update to latest platform rig and core * Bump typescript * Bump typescript * Rollback eslint plugins * Fix lock file * Bump platform-rig * Update to latest platform-rig * update to latest platform-rig * Allow to compile svelte files * Add ui-test component for checking compile * Fix log levels rename compile ui -> compile ui-esbuild * Fix build * Bump esbuild svelte version * Chore: use fixed versions in update-deps Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com> * Chore: commit changes Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com> * Update deps * Add tests for session manager * Fix txOrdering implementation * Bump ordering * Prevent metrics zero values in measure + Fix format svelte files * Revert update-deps script logic * v0.7.19 * update to latest platform-rig * Update deps * Fix pnpm * Session counters * Fix pnpm lock * Add storage client Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Bump versions Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * fix versions Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Bump core * Fix pnpm * Get rid of communication dependency * Add copilot memory file * Use proper name for instructions file * Fix instructions * Use domain instead of test name in gauges * Update instructions file * fix front service upload Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * remove incorrect test Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Move packages to huly.core * Move packages to core, since they are not utils * Add global user profile Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com> * Fix lock file Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com> * Add support for memory limit check * Bump version * Fix pnpm * report more accurate upload progress Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * fic validation issues Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Fix deps Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com> * Move LowLevelStorage to server * Fix linting * Revert "Fix linting" This reverts commit54631d353e. * Revert "Move LowLevelStorage to server" This reverts commitaafb8f6f12. * feature: add regorus engine with permit file Signed-off-by: Leonid Kaganov <lleo@lleo.me> * Fix one second counters for memory usage * Fix kafka test * use fresh core * Version bump * fix: key parameter added Signed-off-by: Leonid Kaganov <lleo@lleo.me> * Fix readme and few author mistakes * Export domain schemas * Bump version * Tests (#117) Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com> * Bump version Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com> * feat: compact compact worker (#4) Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * bump version -> 0.1.16 Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Add TypeIdentifier Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Add change logs Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * rename send -> try_send Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Bump Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Fix pnpm lock Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Add identifier middleware, bump core Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Add subsciption methods to account client Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com> * Fix lock file Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com> * Fix reaction notification (#118) Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com> * Bump version Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com> * Improve find methods schemas to convert to valid types Signed-off-by: Nikolay Marchuk <nikolay.marchuk@hardcoreeng.com> * Add change description Signed-off-by: Nikolay Marchuk <nikolay.marchuk@hardcoreeng.com> * Do not transcode while recording Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Open telemetry support Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * use proper content type in multipart upload Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Bump versions Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * fix build (#26) Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Fix peers (#120) Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com> * Bump version Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com> * Add ActivityCollaborativeChange Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Update pnpm Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Allow to suspend errors on with * Fix pnpm cache * update versions * v0.7.17 for all * v0.7.11 * v0.7.14 * remove arc from worker Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * bump version -> 0.1.17 Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Rank for attributes Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Update pnpm Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Fix one second counters * Fix withContext and allow pass options * Fix formatting * Use updated deps * Bump versions * Update deps * Update deps to platform.core * add support for textColor mark Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * add support for textStyle mark Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Bump versions Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Bump versions again Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Fix Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Rework on second timers * fix merge of large blobs feched from s3 Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * bump version -> 0.1.18 Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * New subscription methods in account-client * Update lock file Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com> * Send error on find for wrong domain * Suspend connect custom errors events in traces * Bump client * Bump core * update deps * Fix lock file * Sorting for TypeIdentifier Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Bump version Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * add workspace usage info Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Bump versions Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> * Improve pg security perfomance Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Fix identifier middleware Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Update TxAccessLevel interface Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com> * Allow guest to update its identities Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com> * Add password login locked platform status Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com> * Fix Uptrace normalizeMarkdown errors Signed-off-by: Artem Savchenko <armisav@gmail.com> * Add change log Signed-off-by: Artem Savchenko <armisav@gmail.com> * Add txMatch to permission Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * update pnpm lock Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Bump Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Fix permission middleware Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Fix enum sorting Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Enable formatting check Signed-off-by: Andrey Sobolev <haiodo@gmail.com> * Enable formatting check * Add change Signed-off-by: Andrey Sobolev <haiodo@gmail.com> * Fix Uptrace NaN error Signed-off-by: Artem Savchenko <armisav@gmail.com> * feature: removed actors, improved performance Signed-off-by: Leonid Kaganov <lleo@lleo.me> * feature: ping from server to clients added Signed-off-by: Leonid Kaganov <lleo@lleo.me> * feature: ping from server to clients added Signed-off-by: Leonid Kaganov <lleo@lleo.me> * Compress kafka messages and fix exception in findAll Signed-off-by: Artem Savchenko <armisav@gmail.com> * Bump versions Signed-off-by: Artem Savchenko <armisav@gmail.com> * Bump versions Signed-off-by: Artem Savchenko <armisav@gmail.com> * Rush change Signed-off-by: Artem Savchenko <armisav@gmail.com> * Fix compression param Signed-off-by: Artem Savchenko <armisav@gmail.com> * Trigger change Signed-off-by: Artem Savchenko <armisav@gmail.com> * Clean up Signed-off-by: Artem Savchenko <armisav@gmail.com> * Trigger change Signed-off-by: Artem Savchenko <armisav@gmail.com> * Bump markdown version Signed-off-by: Artem Savchenko <armisav@gmail.com> * Enable sub projects * Fix wrong double symbol scripts * Include foundation packages * Add support for custom exclude filters Add support for custom exclude filters - by Andrey Sobolev - haiodo@gmail.com Signed-off-by: Andrey Sobolev <haiodo@gmail.com> * Bump Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> * Fix Uptrace filter is not a function error Signed-off-by: Artem Savchenko <armisav@gmail.com> * Sync versions Signed-off-by: Andrey Sobolev <haiodo@gmail.com> --------- Signed-off-by: Leonid Kaganov <lleo@lleo.me> Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com> Signed-off-by: Kristina Fefelova <kristin.fefelova@gmail.com> Signed-off-by: Alexey Zinoviev <alexey.zinoviev@xored.com> Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com> Signed-off-by: Nikolay Marchuk <nikolay.marchuk@hardcoreeng.com> Signed-off-by: Artem Savchenko <armisav@gmail.com> Signed-off-by: Andrey Sobolev <haiodo@gmail.com> Co-authored-by: Leonid Kaganov <lleo@lleo.me> Co-authored-by: Alexander Onnikov <Alexander.Onnikov@xored.com> Co-authored-by: Alexander Onnikov <Alexander.Onnikov@gmail.com> Co-authored-by: Kristina <kristin.fefelova@gmail.com> Co-authored-by: Alexey Zinoviev <alexey.zinoviev@xored.com> Co-authored-by: Denis Bykhov <bykhov.denis@gmail.com> Co-authored-by: Nikolay Marchuk <nikolay.marchuk@hardcoreeng.com> Co-authored-by: Alexander Onnikov <aonnikov@hardcoreeng.com> Co-authored-by: Artem Savchenko <armisav@gmail.com>
416 lines
12 KiB
TypeScript
416 lines
12 KiB
TypeScript
/**
|
|
* Example 5: Error Handling and Retry Logic
|
|
*
|
|
* This example demonstrates robust error handling patterns including:
|
|
* - Exponential backoff retry logic
|
|
* - Graceful degradation
|
|
* - Timeout handling
|
|
* - Connection recovery
|
|
*
|
|
* @example
|
|
* // Start the network server first:
|
|
* // cd pods/network-pod && rushx dev
|
|
*
|
|
* // Then run this example:
|
|
* // cd examples && rushx run:retry
|
|
*/
|
|
|
|
import { AgentImpl, TickManagerImpl, NetworkImpl } from '@hcengineering/network-core'
|
|
import { NetworkServer } from '@hcengineering/network-server'
|
|
import { createNetworkClient, NetworkAgentServer } from '@hcengineering/network-client'
|
|
import type {
|
|
Container,
|
|
ContainerUuid,
|
|
ClientUuid,
|
|
ContainerKind,
|
|
GetOptions
|
|
} from '@hcengineering/network-core'
|
|
|
|
class UnreliableServiceContainer implements Container {
|
|
private callCount = 0
|
|
private failureRate = 0.3 // 30% failure rate
|
|
|
|
constructor(readonly uuid: ContainerUuid) {
|
|
console.log(`[UnreliableService] Container ${uuid} created`)
|
|
}
|
|
|
|
async request(operation: string, data?: any, clientId?: ClientUuid): Promise<any> {
|
|
this.callCount++
|
|
|
|
// Simulate random failures
|
|
if (Math.random() < this.failureRate) {
|
|
console.log(`[UnreliableService] ❌ Request ${this.callCount} failed (simulated)`)
|
|
throw new Error(`Service temporarily unavailable (call ${this.callCount})`)
|
|
}
|
|
|
|
// Simulate slow responses occasionally
|
|
const delay = Math.random() > 0.7 ? 2000 : 100
|
|
await new Promise(resolve => setTimeout(resolve, delay))
|
|
|
|
console.log(`[UnreliableService] ✓ Request ${this.callCount} succeeded`)
|
|
return {
|
|
success: true,
|
|
operation,
|
|
callNumber: this.callCount,
|
|
data: data?.value ? data.value * 2 : null
|
|
}
|
|
}
|
|
|
|
async ping(): Promise<void> {}
|
|
|
|
async terminate(): Promise<void> {
|
|
console.log(`[UnreliableService] Terminated after ${this.callCount} calls`)
|
|
}
|
|
|
|
connect(clientId: ClientUuid, broadcast: (data: any) => Promise<void>): void {}
|
|
disconnect(clientId: ClientUuid): void {}
|
|
}
|
|
|
|
// Retry helper with exponential backoff
|
|
async function retryWithBackoff<T>(
|
|
operation: () => Promise<T>,
|
|
maxRetries = 3,
|
|
initialDelay = 1000,
|
|
maxDelay = 10000
|
|
): Promise<T> {
|
|
let lastError: Error | undefined
|
|
|
|
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
try {
|
|
console.log(` Attempt ${attempt}/${maxRetries}...`)
|
|
const result = await operation()
|
|
console.log(` ✓ Success on attempt ${attempt}`)
|
|
return result
|
|
} catch (error: any) {
|
|
lastError = error
|
|
console.log(` ✗ Attempt ${attempt} failed: ${error.message}`)
|
|
|
|
if (attempt < maxRetries) {
|
|
const delay = Math.min(initialDelay * Math.pow(2, attempt - 1), maxDelay)
|
|
console.log(` Waiting ${delay}ms before retry...`)
|
|
await new Promise(resolve => setTimeout(resolve, delay))
|
|
}
|
|
}
|
|
}
|
|
|
|
throw new Error(`Operation failed after ${maxRetries} attempts: ${lastError?.message}`)
|
|
}
|
|
|
|
// Robust container access with retry and cleanup
|
|
async function robustContainerAccess(
|
|
client: any,
|
|
kind: ContainerKind,
|
|
options: GetOptions,
|
|
operation: string,
|
|
data?: any,
|
|
maxRetries = 3,
|
|
acquireTimeoutMs = 5000
|
|
): Promise<any> {
|
|
let containerRef: any
|
|
|
|
try {
|
|
// Get container with retry and timeout
|
|
containerRef = await retryWithBackoff(async () => {
|
|
return await withTimeout(
|
|
client.get(kind, options),
|
|
acquireTimeoutMs,
|
|
'Container acquisition'
|
|
)
|
|
}, maxRetries)
|
|
|
|
console.log(`✓ Container acquired: ${containerRef.uuid}`)
|
|
|
|
// Perform operation with retry
|
|
const result = await retryWithBackoff(async () => {
|
|
return await containerRef.request(operation, data)
|
|
}, maxRetries)
|
|
|
|
return result
|
|
} catch (error: any) {
|
|
console.error(`✗ All attempts failed: ${error.message}`)
|
|
throw error
|
|
} finally {
|
|
// Always cleanup
|
|
if (containerRef) {
|
|
try {
|
|
await containerRef.close()
|
|
console.log('✓ Container released')
|
|
} catch (err: any) {
|
|
console.error('✗ Failed to release container:', err.message)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Timeout wrapper
|
|
async function withTimeout<T>(
|
|
promise: Promise<T>,
|
|
timeoutMs: number,
|
|
operation: string
|
|
): Promise<T> {
|
|
return Promise.race([
|
|
promise,
|
|
new Promise<T>((_, reject) =>
|
|
setTimeout(() => reject(new Error(`${operation} timed out after ${timeoutMs}ms`)), timeoutMs)
|
|
)
|
|
])
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
console.log('=== Error Handling and Retry Logic Example ===\n')
|
|
|
|
// 1. Setup infrastructure
|
|
const tickManager = new TickManagerImpl(1)
|
|
tickManager.start()
|
|
const network = new NetworkImpl(tickManager)
|
|
const server = new NetworkServer(network, tickManager, '*', 3737)
|
|
console.log('✓ Network server started\n')
|
|
|
|
// 2. Create agent
|
|
const agent = new AgentImpl('unreliable-agent' as any, {
|
|
['unreliable-service' as ContainerKind]: async (options: GetOptions) => {
|
|
const uuid = options.uuid ?? `unreliable-${Date.now()}` as ContainerUuid
|
|
const container = new UnreliableServiceContainer(uuid)
|
|
return {
|
|
uuid,
|
|
container,
|
|
endpoint: `unreliable://localhost/${uuid}` as any
|
|
}
|
|
}
|
|
})
|
|
|
|
const agentServer = new NetworkAgentServer(tickManager, 'localhost', '*', 3738)
|
|
await agentServer.start(agent)
|
|
console.log('✓ Agent server started\n')
|
|
|
|
// 3. Connect client
|
|
await using client = createNetworkClient('localhost:3737')
|
|
|
|
try {
|
|
await withTimeout(
|
|
client.waitConnection(10000),
|
|
5000,
|
|
'Client connection'
|
|
)
|
|
console.log('✓ Client connected\n')
|
|
} catch (error: any) {
|
|
console.error('✗ Failed to connect:', error.message)
|
|
throw error
|
|
}
|
|
|
|
// 4. Register agent
|
|
await client.register(agent)
|
|
console.log('✓ Agent registered\n')
|
|
|
|
// 5. Test basic retry logic
|
|
console.log('=== Test 1: Basic Retry with Backoff ===\n')
|
|
try {
|
|
const result = await robustContainerAccess(
|
|
client,
|
|
'unreliable-service' as ContainerKind,
|
|
{},
|
|
'process',
|
|
{ value: 42 }
|
|
)
|
|
console.log('Final result:', result)
|
|
} catch (error: any) {
|
|
console.error('Operation failed:', error.message)
|
|
}
|
|
console.log()
|
|
|
|
// 6. Test multiple concurrent requests with error handling
|
|
console.log('=== Test 2: Concurrent Requests with Individual Error Handling ===\n')
|
|
const promises = []
|
|
for (let i = 0; i < 5; i++) {
|
|
promises.push(
|
|
robustContainerAccess(
|
|
client,
|
|
'unreliable-service' as ContainerKind,
|
|
{},
|
|
'process',
|
|
{ value: i + 1 }
|
|
).then(result => ({ success: true, result }))
|
|
.catch(error => ({ success: false, error: error.message }))
|
|
)
|
|
}
|
|
|
|
const results = await Promise.all(promises)
|
|
results.forEach((result, idx) => {
|
|
if (result.success) {
|
|
console.log(`Request ${idx + 1}: ✓ Success -`, result.result)
|
|
} else {
|
|
console.log(`Request ${idx + 1}: ✗ Failed -`, result.error)
|
|
}
|
|
})
|
|
console.log()
|
|
|
|
// 7. Test timeout handling
|
|
console.log('=== Test 3: Timeout Handling ===\n')
|
|
try {
|
|
const containerRef = await withTimeout(
|
|
client.get('unreliable-service' as ContainerKind, {}),
|
|
3000,
|
|
'Container acquisition'
|
|
)
|
|
console.log(`✓ Container acquired: ${containerRef.uuid}\n`)
|
|
|
|
// Try with short timeout (likely to timeout on slow responses)
|
|
for (let i = 0; i < 3; i++) {
|
|
try {
|
|
console.log(`Request ${i + 1} with 500ms timeout...`)
|
|
const result = await withTimeout(
|
|
containerRef.request('process', { value: i }),
|
|
500,
|
|
'Request'
|
|
)
|
|
console.log(' ✓ Completed:', result)
|
|
} catch (error: any) {
|
|
console.log(' ✗', error.message)
|
|
}
|
|
}
|
|
|
|
await containerRef.close()
|
|
} catch (error: any) {
|
|
console.log(' ✗ Could not acquire container:', error.message)
|
|
}
|
|
console.log()
|
|
|
|
// 8. Test graceful degradation
|
|
console.log('=== Test 4: Graceful Degradation ===\n')
|
|
|
|
async function getDataWithFallback(id: number) {
|
|
try {
|
|
// Try primary service
|
|
const result = await robustContainerAccess(
|
|
client,
|
|
'unreliable-service' as ContainerKind,
|
|
{},
|
|
'process',
|
|
{ value: id },
|
|
2 // Fewer retries for faster fallback
|
|
)
|
|
return { source: 'primary', data: result }
|
|
} catch (error) {
|
|
console.log('Primary service failed, using fallback...')
|
|
// Fallback to cached/default data
|
|
return {
|
|
source: 'fallback',
|
|
data: {
|
|
success: true,
|
|
operation: 'process',
|
|
value: id,
|
|
cached: true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
const dataResults = []
|
|
for (let i = 0; i < 3; i++) {
|
|
const data = await getDataWithFallback(i + 1)
|
|
dataResults.push(data)
|
|
console.log(`Data ${i + 1}: from ${data.source} -`, data.data)
|
|
}
|
|
console.log()
|
|
|
|
// 9. Test circuit breaker pattern
|
|
console.log('=== Test 5: Circuit Breaker Pattern ===\n')
|
|
|
|
class CircuitBreaker {
|
|
private failureCount = 0
|
|
private lastFailureTime = 0
|
|
private state: 'closed' | 'open' | 'half-open' = 'closed'
|
|
|
|
constructor(
|
|
private readonly failureThreshold = 3,
|
|
private readonly resetTimeout = 5000
|
|
) {}
|
|
|
|
async execute<T>(operation: () => Promise<T>): Promise<T> {
|
|
// Check if circuit should reset
|
|
if (this.state === 'open') {
|
|
if (Date.now() - this.lastFailureTime > this.resetTimeout) {
|
|
console.log(' [CircuitBreaker] Half-open: Trying again...')
|
|
this.state = 'half-open'
|
|
} else {
|
|
throw new Error('Circuit breaker is OPEN - service unavailable')
|
|
}
|
|
}
|
|
|
|
try {
|
|
const result = await operation()
|
|
|
|
// Success - reset circuit breaker
|
|
if (this.state === 'half-open') {
|
|
console.log(' [CircuitBreaker] Closed: Service recovered')
|
|
}
|
|
this.failureCount = 0
|
|
this.state = 'closed'
|
|
|
|
return result
|
|
} catch (error) {
|
|
this.failureCount++
|
|
this.lastFailureTime = Date.now()
|
|
|
|
if (this.failureCount >= this.failureThreshold) {
|
|
console.log(` [CircuitBreaker] OPEN: ${this.failureCount} failures detected`)
|
|
this.state = 'open'
|
|
}
|
|
|
|
throw error
|
|
}
|
|
}
|
|
|
|
getState() {
|
|
return { state: this.state, failures: this.failureCount }
|
|
}
|
|
}
|
|
|
|
const breaker = new CircuitBreaker(2, 3000)
|
|
|
|
for (let i = 0; i < 5; i++) {
|
|
try {
|
|
const result = await breaker.execute(async () => {
|
|
return await robustContainerAccess(
|
|
client,
|
|
'unreliable-service' as ContainerKind,
|
|
{},
|
|
'process',
|
|
{ value: i },
|
|
1 // Single retry
|
|
)
|
|
})
|
|
console.log(`Request ${i + 1}: ✓`, result)
|
|
} catch (error: any) {
|
|
console.log(`Request ${i + 1}: ✗`, error.message)
|
|
}
|
|
console.log(' Circuit breaker state:', breaker.getState())
|
|
await new Promise(resolve => setTimeout(resolve, 500))
|
|
}
|
|
console.log()
|
|
|
|
// 10. Cleanup
|
|
console.log('--- Cleanup ---')
|
|
client.close()
|
|
await agentServer.close()
|
|
await server.close()
|
|
tickManager.stop()
|
|
console.log('✓ Cleanup complete')
|
|
|
|
console.log('\n✓ Example completed successfully!')
|
|
console.log('\nKey patterns demonstrated:')
|
|
console.log(' 1. Exponential backoff retry')
|
|
console.log(' 2. Timeout handling')
|
|
console.log(' 3. Graceful degradation with fallbacks')
|
|
console.log(' 4. Circuit breaker pattern')
|
|
console.log(' 5. Proper resource cleanup')
|
|
|
|
// Exit cleanly
|
|
await new Promise(resolve => setTimeout(resolve, 500))
|
|
process.exit(0)
|
|
}
|
|
|
|
main().catch(console.error)
|
|
|
|
export { UnreliableServiceContainer, retryWithBackoff, withTimeout }
|