Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
A library for creating powerful and flexible finite state machines. Loosely inspired by Erlang/OTP's gen_fsm behavior.
Machina.js is a JavaScript framework for highly customizable finite state machines (FSMs). Many of the ideas for machina have been loosely inspired by the Erlang/OTP FSM behaviors.
(Be sure to check out the example folder in this repository for more in-depth demos).
Creating an FSM:
var storageFsm = new machina.Fsm({
applicationOffline: function() {
var offline = false;
// checks window.navigator.online and more, sets the offline value
return offline;
},
verifyState: function( payload ) {
if( applicationOffline() && this.state !== "offline" ) {
this.offlineMarkerTime = new Date();
this.transition("offline");
return false;
}
else if ( !applicationOffline() && this.state === "offline" ) {
this.transition( "online" );
return false;
}
return true;
},
initialState: "offline",
states : {
"online" : {
_onEnter: function() {
this.handle("sync.customer");
},
"save.customer" : function( payload ) {
if( verifyState( payload ) ) {
storage.saveToRemote( payload );
}
},
"sync.customer" : function() {
if( verifyState( payload ) ) {
var unsynced = storage.getFromLocal( { startTime: this.offlineMarkerTime } );
// Big assumption here! In the real world,
// we'd batch this sync in reasonable chunks.
storage.saveBatchToRemote( unsynced );
this.fireEvent( "CustomerSyncComplete", { customers: unsynced } );
}
}
},
"offline" : {
"save.customer" : function( payload ) {
if( verifyState( payload ) ) {
storage.saveToLocal( payload );
}
}
}
}
});
In the above example, the developer has created an FSM with two possible states: online
and offline
. While the fsm is in the online
state, it will respond to save.customer
and sync.customer
events. External code triggers these events by calling the handle
method on the FSM. For example storageFsm.handle( "sync.customer", { other: "data" } )
. The handle
method first looks to see if a named handler exists matching the name of the one passed in, then also checks for a catch-all handler (indicated by the "*") if a named handler isn't found. The offline
state of the above FSM only responds to save.customer
events. If any other type of event name is passed to the handle
method of the FSM, other than what each state explicitly handles, it is ignored.
In addition to the state/handler definitions, the above code example as shows that the FSM will start in the offline
state, and can generate a CustomerSyncComplete
event.
The verifyState
and applicationOffline
methods are custom to this instance of the FSM, and are not, of course, part of machina by default.
You can see in the above example that anytime the FSM handles an event, it first checks to see if the state needs to be transitioned between offline and online (via the verifyState
call). States can also have an _onEnter
method - which is fired immediately after the FSM transitions into that state.
Now that we've seen a quick example, let's do a whirlwind API tour.
When you are creating a new FSM instance, machina.Fsm
takes 1 argument - an options object. Here's a breakdown of the members of this options
object:
eventListeners
- Either a list of event names that the FSM can publish, or an object of event names, associated with the array of event handlers subscribed to them. (You are not required to declare the events your FSM can publish ahead of time - this is only for convenience if you want to add handlers ahead of time.)
eventListeners: ["String", "List", "ofEvent", "names"]; // this is converted into an object similar to below
// OR
eventListeners: {
MyEvent1: [],
MyEvent2: [function(data) { console.log(data); }]
}
states
- an object detailing the possible states the FSM can be in, plus the kinds of events/messages each state can handle. States can have normal "handlers" as well as a catch-all handler ("*"), and an _onEnter handler invoked when the FSM has transitioned into that state.
states: {
"uninitialized" : {
_onEnter: function() {
// do stuff immediately after we transition into uninitialized
},
"initialize" : function( payload ) {
// handle an "initialize" event
}
},
"ready" : {
"*" : function( payload ) {
// any message that comes while in the "ready" state will get handled here
// unless it matches another "ready" handler exactly.
}
}
initialState
- the state in which the FSM will start. As soon as the instance is created, the FSM calls the transition
method to transition into this state.
namespace
- a name that indentifies the FSM if it's wired up to a message bus through a plugin.
Each instance of an machina FSM has the following methods available via it's prototype:
fireEvent(eventName, [other args...])
- looks in the events
object for a matching event name, and then iterates through the subscriber callbacks for that event and invokes each one, passing in any additional args that were passed to fireEvent
.handle(msgType, [other args...])
- This is the main way you should be interacting with an FSM instance (assuming no message bus is present). It will try to find a matching eventName/msgType under the current state and invoke it, if one exists. Otherwise it will look for a catch-all handler, or simply ignore the message and raise the "NoHandler" event.transition(newState)
- Called when transitioning into a new state.deferUntilTransition(stateName)
- calling this within a state handler function will queue the handler's arguments to be executed at a later time. If you don't provide the stateName
argument, it will replay the event after the next state transition. Providing the stateName
argument will queue the event until the FSM transitions into that state.deferUntilNextHandler()
- calling this within a state handler function will queue the handler's arguments to be executed after the next handler is invoked.processQueue()
- called internally during state transitions and after handler methods have been invoked. This call processes any queued events (queued by use of deferUntilTransition
and/or deferUntilNextHandler
).on(eventName, callback)
- used to subscribe to events that the FSM generates.off(eventName, callback)
- used to unsubscribe to FSM events.In addition to the prototype members, every instance of an FSM has these instance-specific values as well:
state
- string value of the current state of the FSM. This will match one of the state names in the states
object. Do not change this value directly. Use the transition()
method on the prototype to change an FSM's state.priorState
- the last state in which the FSM was in before the current one. This could be useful if you have conditional transition behavior as you move into a new state which depends on what state you're moving from._currentAction
- concatenates "{state}.{handler}" for the operation in progress. This is provided as a convenience for both logging (if needed) and if you need to check during an operation to see if the last action taken is the same action being taken now._priorAction
- concatenates "{state}.{handler" for the last operation that took place. See the above explanation for more context.The top level machina
object has the following members:
Fsm
- the constructor function used to create FSMs.utils
- contains helper functions that can be overridden to change default behavior(s) in machina:
getDefaultOptions
- returns the default options object for any machina instancemakeFsmNamespace
- function that provides a default "channel" or "exchange" for an FSM instance. (e.g. - fsm.0, fsm.1, etc.)on
- function used to subscribe a callback to top-level machina events (currently the only event published at this level is "newFsm")off
- function used to unsubscribe a callback to top-level machina events.eventListeners
- an object literal containing the top-level fireEvent
call as well as susbcribers to any top-level events.machina.js uses anvil.js to build.
npm install -g anvil.js
to install anvil.jsanvil -b
One great feature of anvil.js is the ability to host your tests and other content using express in node.js. To run tests or examples:
anvil --host
http://localhost:3080/spec
http://localhost:3080/atm
http://localhost:3080/load
v0.2.1
FAQs
A library for creating powerful and flexible finite state machines. Loosely inspired by Erlang/OTP's gen_fsm behavior.
The npm package machina receives a total of 22,495 weekly downloads. As such, machina popularity was classified as popular.
We found that machina demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.