4using System.Threading.Tasks;
35 [CollectionName(
"StateMachines")]
37 [ArchivingTime(nameof(ArchiveDays))]
38 [Index(
"StateMachineId")]
39 [Index(
"CreatorTokenId")]
40 [Index(
"Expires",
"StateMachineId")]
41 [ObsoleteMethod(nameof(SetObsoleteProperties))]
44 private Dictionary<string, Model.Actions.Action> actions;
45 private Dictionary<string, Model.Events.Event> events;
46 private Dictionary<string, State> states;
116 this.actions =
new Dictionary<string, Model.Actions.Action>();
117 this.events =
new Dictionary<string, Model.Events.Event>();
118 this.states =
new Dictionary<string, State>();
122 Node.IndexElement(
this);
133 if (this.actions.ContainsKey(
Action.
Id))
145 if (this.events.ContainsKey(
Event.Id))
157 if (this.states.ContainsKey(
State.
Id))
173 Node.CheckReferences(
this,
Token);
192 return this.actions.TryGetValue(Id, out
Action);
209 return this.events.TryGetValue(Id, out
Event);
226 return this.states.TryGetValue(Id, out
State);
240 List<CurrentStateVariable> VariableValues =
new List<CurrentStateVariable>();
244 List<StateMachineSample> Samples =
null;
250 if (Node is Model.Variable
Variable)
254 object Value = await
Variable.Evaluate(Arguments);
259 Samples ??=
new List<StateMachineSample>();
263 Timestamp = DateTime.UtcNow,
273 Log.
Critical(
"Unable to evaluate inital value for variable " +
274 Variable.Id +
" for state-machine. Error reported: " + ex.Message,
this.ObjectId);
279 Timestamp = DateTime.UtcNow,
291 CurrentState.VariableValues = VariableValues.ToArray();
295 if (!(Samples is
null))
317 DateTime
Start = DateTime.Now;
346 Timestamp = DateTime.UtcNow,
354 if (
string.IsNullOrEmpty(StateId))
360 if (!(
State is
null))
375 Timestamp = DateTime.UtcNow,
387 if (!(EventsTriggered is
null))
392 if (!(EventTriggered is
null))
399 await EventTriggered.
ExecuteLog(Arguments, SuppressSamples);
400 StateId = await EventTriggered.
GetNewState(Arguments);
406 if (
string.IsNullOrEmpty(StateId))
413 Timestamp = DateTime.UtcNow,
423 if (!
string.IsNullOrEmpty(StateId))
428 double ElapsedTimeSeconds = DateTime.Now.Subtract(
Start).TotalMinutes;
430 if (ElapsedTimeSeconds > 60)
434 new KeyValuePair<string, object>(
"ElapsedTimeSeconds", ElapsedTimeSeconds));
441 while (!
string.IsNullOrEmpty(StateId));
460 if (StateUpdated || VariablesUpdated || AuthorizationsUpdated)
464 Arguments.AuthorizationsUpdated =
false;
468 Arguments.StateUpdated =
false;
470 if (!(Arguments.
Token is
null))
472 StringBuilder Xml =
new StringBuilder();
475 Xml.Append(
"<stateUpdated xmlns='");
477 Xml.Append(
"' tokenId='");
479 Xml.Append(
"' machineId='");
481 Xml.Append(
"' state='");
485 _ = Task.Run(async () =>
500 if (VariablesUpdated)
502 if (Arguments.
Token is
null)
507 StringBuilder Xml =
new StringBuilder();
510 Xml.Append(
"<variablesUpdated xmlns='");
512 Xml.Append(
"' tokenId='");
514 Xml.Append(
"' machineId='");
518 foreach (KeyValuePair<string, object> P
in Variables)
521 Xml.Append(
"</variablesUpdated>");
523 _ = Task.Run(async () =>
542 if ((TabIDs?.Length ?? 0) > 0)
563 if (Ref?.Triggered ??
false)
571 bool SuppressSamples = await
Event.GetSuppressSample(Arguments);
572 await
Event.ExecuteLog(Arguments, SuppressSamples);
573 StateId = await
Event.GetNewState(Arguments);
577 StateId = await
Event.GetFailureState(Arguments);
579 if (
string.IsNullOrEmpty(StateId))
586 Timestamp = DateTime.UtcNow,
596 if (!
string.IsNullOrEmpty(StateId))
614 if (ActionReferences is
null)
618 await
Action.ExecuteLog(Arguments, SuppressSamples);
640 if (Ref?.Triggered ??
false)
652 string MachineId =
Event.StateMachine.StateMachineId;
655 Log.
Error(
"Unable to register event handlers for state machine.",
656 new KeyValuePair<string, object>(
"State Machine ID", MachineId),
657 new KeyValuePair<string, object>(
"State",
CurrentState),
658 new KeyValuePair<string, object>(
"Messge", ex.Message),
659 new KeyValuePair<string, object>(
"Event",
Event.
Event.Label),
660 new KeyValuePair<string, object>(
"Local Name",
Event.
Event.LocalName),
661 new KeyValuePair<string, object>(
"Namespace",
Event.
Event.Namespace));
666 Timestamp = DateTime.UtcNow,
690 foreach (EventHandlers.EventHandler Handler in Handlers)
702 await
Event.Unregister(i, Arguments);
732 return Name ==
"this";
742 throw new NotSupportedException(
"Variable collection is read-only.");
784 foreach (KeyValuePair<string, object> Property
in Properties)
786 switch (Property.Key)
788 case "XmlDefinnition":
789 if (Property.Value is
string s)
790 this.XmlDefinition = s;
Helps with common XML-related tasks.
static string Encode(string s)
Encodes a string for use in XML.
static XmlDocument ParseXml(string Xml)
Parses an XML Document from its string representation.
Class representing an event.
Event(DateTime Timestamp, EventType Type, string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
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.
static Exception UnnestException(Exception Exception)
Unnests an exception, to extract the relevant inner exception.
The ClientEvents class allows applications to push information asynchronously to web clients connecte...
static string[] GetTabIDsForLocation(string Location)
Gets the Tab IDs of all tabs that display a particular resource.
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.
A chunked list is a linked list of chunks of objects of type T .
Class that keeps track of events and timing.
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.
Legal (digital identities, smart contracts) service component.
Marketplace processor, brokering sales of items via tenders and offers defined in smart contracts.
bool IsPublic
If the token is public.
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.
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.
CaseInsensitiveString StateMachineId
ID of State-Machine.
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.
Contains information about an event handler reference
virtual Task Prepare(EvaluationArguments Arguments)
Prepares the collection of event arguments for event handler execution.
OnEvent Event
Event that triggered the event handler, if any.
Exception related to state machine.
Represents an action definition.
Abstract base class for nodes referencing an action.
async Task< TimeSpan > ExecuteLog(EvaluationArguments Arguments, bool SuppressSample)
Evaluates an action, and logs the time the action took as a sample value.
Defines an expiry timestamp.
Expires()
Defines an expiry timestamp.
Defines the name of a variable.
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< bool > GetSuppressSample(EvaluationArguments Arguments)
Gets a Boolean value indicating if samples should be suppressed for the event.
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 ReparseDefinition()
Reparses the state-machine.
async Task< RequestOrigin > GetOrigin()
Origin of request.
void Index(Model.Events.Event Event)
Adds an event to the index.
static async Task< ChunkedList< EventHandlerReference > > RegisterEventHandlers(OnEvent[] Events, EvaluationArguments Arguments)
Registers a set of events.
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
CaseInsensitiveString CreatorTokenId
ID of token that created the state-machine.
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.
Duration? ArchiveOptional
Duration after which token expires, and the required archiving time, the token can optionally be arch...
bool HasPrivilege(string Privilege)
If the origin has a given privilege.
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.
static async Task ExecuteLog(ActionReference[] ActionReferences, EvaluationArguments Arguments, bool SuppressSamples)
Evaluates a set of actions.
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.
const string ExceptionVariable
Variable ID used to sample exception messages.
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....