Created
July 24, 2018 01:53
-
-
Save jonkirkman/07554e33cd15c19d60c258ca2166dfd6 to your computer and use it in GitHub Desktop.
not actually distributed
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
import 'dart:async'; | |
enum SagaStates { created, executing, compensating, succeeded, failed } | |
class Saga { | |
String id; | |
String label; | |
SagaStates _state = SagaStates.created; | |
Set<Opperation> opperations; | |
List<Future> _opperations; | |
Saga() {} | |
set state(SagaStates s) { | |
_state = s; | |
// TODO: publish the change | |
// TODO: commit the state to storage | |
} | |
get state => _state; | |
execute() { | |
state = SagaStates.executing; | |
_opperations = opperations.map((Opperation op) => op.execute()); | |
Future.wait(_opperations, eagerError: true) | |
.then(_onSuccess) | |
.catchError(compensate); | |
} | |
compensate() { | |
state = SagaStates.compensating; | |
_opperations = opperations.map((Opperation op) => op.compensate()); | |
Future.wait(_opperations).whenComplete(_ensureCompensated); | |
} | |
_ensureCompensated() { | |
_opperations = opperations | |
.where((Opperation op) => op.state != SagaStates.compensating) | |
.map((Opperation op) => op.compensate()); | |
if (_opperations.isEmpty) { | |
_onFailure(); | |
} else { | |
Future.wait(_opperations).whenComplete(_ensureCompensated); | |
} | |
} | |
_onSuccess(List results) { | |
state = SagaStates.succeeded; | |
} | |
_onFailure() { | |
state - SagaStates.failed; | |
} | |
} | |
class Opperation { | |
String id; | |
String label; | |
SagaStates state; | |
Future execute() {} | |
Future compensate() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment