2using System.Collections.Generic;
4using System.Threading.Tasks;
30 [CollectionName(
"StateMachines")]
32 [ArchivingTime(nameof(ArchiveDays))]
33 [Index(
"StateMachineId")]
34 [Index(
"Expires",
"StateMachineId")]
35 [ObsoleteMethod(nameof(SetObsoleteProperties))]
38 private Dictionary<string, Model.Actions.Action> actions;
39 private Dictionary<string, Model.Events.Event> events;
40 private Dictionary<string, State> states;
110 this.actions =
new Dictionary<string, Model.Actions.Action>();
111 this.events =
new Dictionary<string, Model.Events.Event>();
112 this.states =
new Dictionary<string, State>();
116 Node.IndexElement(
this);
127 if (this.actions.ContainsKey(
Action.
Id))
128 throw new Exception(
"Duplicate Action ID: " +
Action.
Id);
139 if (this.events.ContainsKey(
Event.Id))
140 throw new Exception(
"Duplicate Event ID: " +
Event.Id);
151 if (this.states.ContainsKey(
State.
Id))
152 throw new Exception(
"Duplicate State ID: " +
State.
Id);
167 Node.CheckReferences(
this,
Token);
186 return this.actions.TryGetValue(Id, out
Action);
203 return this.events.TryGetValue(Id, out
Event);
220 return this.states.TryGetValue(Id, out
State);
233 List<CurrentStateVariable> VariableValues =
new List<CurrentStateVariable>();
237 List<StateMachineSample> Samples =
null;
243 if (Node is Model.Variable
Variable)
247 object Value = await
Variable.Evaluate(Arguments);
253 Samples =
new List<StateMachineSample>();
258 Timestamp = DateTime.UtcNow,
268 Log.
Critical(
"Unable to evaluate inital value for variable " +
269 Variable.Id +
" for state-machine. Error reported: " + ex.Message,
this.ObjectId);
275 CurrentState.VariableValues = VariableValues.ToArray();
279 if (!(Samples is
null))
301 DateTime
Start = DateTime.Now;
321 throw new Exception(
"State not found:" + StateId);
330 Timestamp = DateTime.UtcNow,
341 if (!(
State is
null))
343 IEnumerable<OnEvent> EventsTriggered =
null;
357 if (!(EventsTriggered is
null))
359 foreach (
OnEvent EventTriggered
in EventsTriggered)
364 StateId = await EventTriggered.
GetNewState(Arguments);
370 if (
string.IsNullOrEmpty(StateId))
374 if (!
string.IsNullOrEmpty(StateId))
378 double ElapsedTimeSeconds = DateTime.Now.Subtract(
Start).TotalMinutes;
380 if (ElapsedTimeSeconds > 60)
384 new KeyValuePair<string, object>(
"ElapsedTimeSeconds", ElapsedTimeSeconds));
391 while (!
string.IsNullOrEmpty(StateId));
410 if (StateUpdated || VariablesUpdated || AuthorizationsUpdated)
414 Arguments.AuthorizationsUpdated =
false;
418 Arguments.StateUpdated =
false;
420 if (!(Arguments.
Token is
null))
422 StringBuilder Xml =
new StringBuilder();
425 Xml.Append(
"<stateUpdated xmlns='");
427 Xml.Append(
"' tokenId='");
429 Xml.Append(
"' machineId='");
431 Xml.Append(
"' state='");
438 if (VariablesUpdated)
443 if (VariablesUpdated)
445 if (Arguments.
Token is
null)
450 StringBuilder Xml =
new StringBuilder();
453 Xml.Append(
"<variablesUpdated xmlns='");
455 Xml.Append(
"' tokenId='");
457 Xml.Append(
"' machineId='");
461 foreach (KeyValuePair<string, object> P
in Variables)
464 Xml.Append(
"</variablesUpdated>");
486 if (await
Event.StateUpdated(Arguments))
492 await
Event.ExecuteLog(Arguments);
493 StateId = await
Event.GetNewState(Arguments);
497 StateId = await
Event.GetFailureState(Arguments);
499 if (
string.IsNullOrEmpty(StateId))
503 if (!
string.IsNullOrEmpty(StateId))
520 if (ActionReferences is
null)
524 await
Action.ExecuteLog(Arguments);
539 LinkedList<OnEvent> Result =
null;
543 if (await
Event.Register(i++, Arguments))
546 Result =
new LinkedList<OnEvent>();
548 Result.AddLast(
Event);
566 foreach (EventHandlers.EventHandler Handler in Handlers)
578 await
Event.Unregister(i, Arguments);
608 return Name ==
"this";
618 throw new NotSupportedException(
"Variable collection is read-only.");
637 XmlDocument Doc =
new XmlDocument();
651 foreach (KeyValuePair<string, object> Property
in Properties)
653 switch (Property.Key)
655 case "XmlDefinnition":
656 if (Property.Value is
string s)
657 this.XmlDefinition = s;
Helps with common XML-related tasks.
static string Encode(string s)
Encodes a string for use in XML.
Class representing an event.
Static class managing the application event log. Applications and services log events on this static ...
static void Exception(Exception Exception, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, params KeyValuePair< string, object >[] Tags)
Logs an exception. Event type will be determined by the severity of the exception.
static void Critical(string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
Logs a critical event.
static void Error(string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
Logs an error event.
XmppAddress MainDomain
Main/principal domain address
XmppServer Server
XMPP Server.
Contains information about one XMPP address.
override string ToString()
object.ToString()
Task< bool > SendMessage(string Type, string Id, string From, string To, string Language, string ContentXml)
Sends a Message stanza to a recipient.
Represents a case-insensitive string.
string Value
String-representation of the case-insensitive string. (Representation is case sensitive....
Static interface for database persistence. In order to work, a database provider has to be assigned t...
static Task< IEnumerable< object > > FindDelete(string Collection, params string[] SortOrder)
Finds objects in a given collection and deletes them in the same atomic operation.
static async Task Update(object Object)
Updates an object in the database.
static async Task Insert(object Object)
Inserts an object into the default collection of the database.
This filter selects objects that conform to all child-filters provided.
This filter selects objects that have a named field equal to a given value.
Class that keeps track of events and timing.
Contains information about a variable.
Variable(string Name, IElement Value)
Contains information about a variable.
virtual Variable Add(string Name, object Value)
Adds a variable to the collection.
Manages eDaler on accounts connected to the broker.
Provisioning and registry service component.
Marketplace processor, brokering sales of items via tenders and offers defined in smart contracts.
static int CalcArchiveDays(DateTime Expires, Duration? ArchiveReq, Duration? ArchiveOpt)
Calculates the number of days an object should be archived in the ledger.
CaseInsensitiveString OwnerJid
JID of Current owner of token
CaseInsensitiveString TokenId
Token ID
Class representing the current state of a state machine.
string StateMachineId
ID of State-Machine.
Variables GetVariables(StateMachine Machine)
Gets a new variable collection containing the current state variables.
string State
ID of current state in state-machine. Empty State = State-machine has ended.
Class representing a persisted state-machine variable value.
Abstract base class for cached event handlers.
async Task RemoveFromCache()
Removes the event handler from the cache.
Represents an action definition.
Abstract base class for nodes referencing an action.
async Task< TimeSpan > ExecuteLog(EvaluationArguments Arguments)
Evaluates an action, and logs the time the action took as a sample value.
Contains information required for evaluating script in a state-machine.
StateMachine Machine
Reference to state-machine definition.
CurrentState CurrentState
Current persisted state.
EDalerComponent EDaler
eDaler component.
bool AuthorizationsUpdated
If authorizations in the state machine have been updated.
KeyValuePair< string, object >[] PopUpdatedVariables()
Gets an array of updated variables since last call.
bool StateUpdated
If the state machine has changed state during processing.
void ClearUpdatedVariables()
Clears the variable update flags.
bool VariablesUpdated
If variables in the state machine have been updated.
Token Token
Reference to related token.
void SetState(string StateId)
Sets a new state.
bool ForEach(ForEachCallback Callback, object State)
Iterates through th node and all its child nodes.
IStateMachineNode[] ChildNodes
Child nodes, if available. Null if no children.
Root of the State-Machine definition
string StartState
Start State of state-machine.
Action executed when entering a state.
async Task< string > GetFailureState(EvaluationArguments Arguments)
Gets the failure state ID when the event is triggered.
async Task< string > GetNewState(EvaluationArguments Arguments)
Gets the new state ID when the event is triggered.
Represents an action definition.
OnEnter[] OnEnter
Events raised when entering the state.
OnLeave[] OnLeave
Events raised when leaving the state.
OnEvent[] OnEvent
Events that can be raised when in the state.
Class representing a state machine.
StateMachineRoot Root
Root of State-Machine model.
bool TryGetAction(string Id, out Model.Actions.Action Action)
Tries to get an action.
bool TryGetState(string Id, out State State)
Tries to get a state.
Duration? ArchiveRequired
Duration after which token expires, the token is required to be archived.
void IndexElements()
Indexes all elements in the state-machine.
async Task<(CurrentState, EvaluationArguments)> CreateCurrentState(Token Token, LegalComponent Legal, EDalerComponent EDaler, Profiler Profiler)
Starts processing of the state-machine.
bool TryGetVariable(string Name, out Script.Variable Variable)
Tries to get a variable object, given its name.
async Task< RequestOrigin > GetOrigin()
Origin of request.
void Index(Model.Events.Event Event)
Adds an event to the index.
static async Task GoToState(string StateId, EvaluationArguments Arguments)
Goes to a new state.
string XmlDefinition
XML Definition.
void SetObsoleteProperties(Dictionary< string, object > Properties)
Sets obsolete properties.
CaseInsensitiveString TrustProviderJid
JID of Trust Provider
void ReparseDefinition()
Reparses the state-machine.
CaseInsensitiveString CreatorTokenId
ID of token that created the state-machine.
static async Task ExecuteLog(ActionReference[] ActionReferences, EvaluationArguments Arguments)
Evaluates a set of actions.
bool TryGetEvent(string Id, out Model.Events.Event Event)
Tries to get an event.
async Task Start(EvaluationArguments Arguments)
Starts the processing of the state-machine.
string ObjectId
Object ID of state machine.
void Index(State State)
Adds a state to the index.
CaseInsensitiveString StateMachineId
ID of State Machine.
void CheckReferences(Token Token)
Indexes all elements in the state-machine.
static async Task EvaluationComplete(EvaluationArguments Arguments)
Method called when current evaluation has been completed, and new states need to be persisted.
static async Task< IEnumerable< OnEvent > > RegisterEventHandlers(OnEvent[] Events, EvaluationArguments Arguments)
Registers a set of events.
Duration? ArchiveOptional
Duration after which token expires, and the required archiving time, the token can optionally be arch...
CaseInsensitiveString DefinitionContractId
ID of Definition Contract
void Index(Model.Actions.Action Action)
Adds an action to the index.
CaseInsensitiveString TrustProvider
ID of Trust Provider
Waher.Script.Variable Add(string Name, object Value)
Adds a variable to the collection.
int ArchiveDays
Number of days to archive field.
DateTime Expires
When state-machine expires
static async Task CheckConditionalEvents(EvaluationArguments Arguments)
Checks conditional events.
static async Task UnregisterEventHandlers(OnEvent[] Events, EvaluationArguments Arguments)
Unregisters event handlers for the current state.
bool ContainsVariable(string Name)
If the collection contains a variable with a given name.
const string StateMachineNamespace
https://paiwise.tagroot.io/Schema/StateMachines.xsd
Class representing a sample of a state machine variable over time.
const string CurrentStateVariable
Variable ID used to sample state changes.
Tokens available in request.
Variables available in a specific context.
Interface for State-Machine nodes
Interface for requestors that can act as an origin for distributed requests.
TypeNameSerialization
How the type name should be serialized.
Represents a duration value, as defined by the xsd:duration data type: http://www....