Skip to content

Instantly share code, notes, and snippets.

@jonkirkman
Created July 24, 2018 01:53
Show Gist options
  • Save jonkirkman/07554e33cd15c19d60c258ca2166dfd6 to your computer and use it in GitHub Desktop.
Save jonkirkman/07554e33cd15c19d60c258ca2166dfd6 to your computer and use it in GitHub Desktop.
not actually distributed
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