Last active
November 10, 2020 11:48
-
-
Save miraklez/39cab7ce22d8065a3be7f3dd63a1fdb7 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
const PingPongStates = { | |
id: 'ping-pong', | |
initial: 'idle', | |
states: { | |
idle: { | |
after: { | |
PING_DELAY: 'waiting' | |
} | |
}, | |
waiting: { | |
entry: 'sendPing', | |
on: { | |
PONG: 'idle', | |
}, | |
after: { | |
PONG_TIMEOUT: { | |
target: '#websocket.failure', | |
message: 'PING-PONG Timeout' | |
} | |
} | |
} | |
} | |
} | |
const MessagesHandlerStates = { | |
id: 'messages', | |
initial: 'idle', | |
states: { | |
idle: {} | |
} | |
} | |
const ConnectedParallelStates = { | |
id: 'connected', | |
type: 'parallel', | |
states: { | |
messages: { ...MessagesHandlerStates }, | |
pingpong: { ...PingPongStates } | |
} | |
} | |
const WebSocketConfig = { | |
id: 'websocket', | |
initial: 'idle', | |
context: { | |
url: undefined, | |
autoConnect: true, | |
retries: 0, | |
maxRetries: 3 | |
}, | |
states: { | |
idle: { | |
on: { | |
OPEN: { | |
target: 'connecting', | |
actions: 'setUrl' | |
} | |
} | |
}, | |
connecting: { | |
on: { | |
SUCCESS: 'connected', | |
ERROR: 'failure' | |
} | |
}, | |
connected: { | |
entry: 'resetRetries', | |
...ConnectedParallelStates, | |
on: { | |
NORMAL_CLOSE: 'idle', | |
ERROR: 'failure' | |
} | |
}, | |
failure: { | |
exit: 'incrementRetries', | |
on: { | |
RETRY: { | |
target: 'connecting', | |
cond: 'isMoreRetries' | |
} | |
}, | |
after: { | |
AUTO_RETRY_DELAY: { | |
target: 'connecting', | |
cond: 'isAutoConnect' | |
} | |
} | |
} | |
} | |
} | |
const WebSocketOptions = { | |
delays: { | |
// linear function depend on number of retries | |
AUTO_RETRY_DELAY: (ctx, ev) => 1500, | |
PING_DELAY: () => 10000, | |
PONG_TIMEOUT: () => 5000 | |
}, | |
actions: { | |
incrementRetries: assign({ | |
retries: (ctx) => ctx.retries +1 | |
}), | |
resetRetries: assign({ retries: 0 }), | |
setUrl: (ctx, ev) => ctx.url = ev.url, | |
sendPing: () => { console.log('send PING') } | |
}, | |
guards: { | |
isAutoConnect: ({ autoConnect, maxRetries, retries }) => autoConnect && maxRetries > retries | |
}, | |
isMoreRetries: ({ retries, maxRetries }) => maxRetries > retries | |
} | |
const websocket = Machine(WebSocketConfig, WebSocketOptions) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment