Saturday, September 9, 2017

State machines for everyday app logic

Finite State machines 

When you look at a feature toggle, an order workflow or a retry loop, it’s easy to think you’re just writing a few if statements. But any time you have a handful of distinct situations and rules about how to move between them, you’re really building a state machine. Most of us just don’t call it that. The result is often a tangle of boolean flags and duplicated logic that’s hard to follow and easy to break.

A finite state machine (FSM) offers a simpler way to describe that behaviour. You list the possible states your system can be in, define the events that cause it to move to a new state, and then enforce that it’s always in exactly one state at a time. Because transitions are explicit, you can’t accidentally be both “loading” and “error” at once, and you know exactly what can happen next. That predictability pays off when a user clicks rapidly or an API retries at odd moments.

Why bother?

  • Clarity and fewer bugs. State machines make “what can happen next?” explicit. Impossible combinations of flags simply disappear. Logs become a clear timeline of state changes rather than a guesswork of booleans.
  • Easier to evolve. When requirements change, you add or adjust transitions instead of unravelling nested conditionals. State machines scale better than growing lists of isLoading, hasError and isRetrying flags.
  • Reuse across layers. A single definition of states and transitions can serve both your backend and your UI. The server exposes the current state and allowed events; the client uses that to drive feedback and button enablement. You avoid duplicating business rules in the interface.
  • Process friendly. Anything that has a start, middle and end benefits from this model: order processing, approval workflows, file uploads, background job pipelines and feature toggles all map neatly to states and transitions.

A tiny example from my own project

I recently built a simple state manager as an internal service and published it as a small GitHub project. Instead of relying on a heavy framework, this manager stores all transitions in a map keyed by the current state and an event. When an event arrives, it looks up the next state and updates the domain object. Because the transition table never changes, the same manager can be reused across threads without any synchronisation. The approach follows the pattern described by Nicholas Blumhardt’s Stateless library: you supply functions to read and update the state rather than letting the machine manage storage. This lightweight implementation replaced a cluster of if statements in an approval workflow and made it obvious which events were valid at each stage. You can see the full code and an example Spring Boot integration in my GitHub repository; it serves as a working example of a simple finite state machine.

To make this example concrete, the implementation is published as the states repository on GitHub. This open‑source “States Manager” stores its transitions in a map of (state, event) pairs and uses injected functions to read and update the current state. Feel free to clone the project to see how a minimal finite state machine works in practice and adapt it to your own workflow.

Getting started

You don’t need a big framework to benefit from state machines. Start by listing your states and the events that change them. Draw a simple diagram or table. Then write a small function that, given a state and an event, returns the next state. As your needs grow, you can add guard conditions or side effects. If your workflow evolves quickly, there is some up‑front effort in naming states and transitions, but once things stabilise, the clarity and reliability pay for themselves. And when correctness matters—orders, payments, approvals—explicit transitions are a big win.

State machines aren’t esoteric theory; they’re a practical tool for everyday application logic. By making the flow explicit and keeping the transition rules separate from your business code, you get systems that are easier to reason about, test and extend. Next time you reach for another else clause, consider whether a simple state machine might serve you—and your future self—better.


🔗 Related post: Why developers never use state machines


Sunday, September 3, 2017

My usefull posts

 Java posts

Blockchain/Smart contacts


REST service Mutual SSL aauthentication

Migrating applications to micro-services means having a couple of applications that need to talk to each other. We need an architecture to allow to add security at method level and to keep our data safe from inside attacks. Much of what will be said here can be applied to non spring based micro-services.

Oauth2, our best friend

This is an authorization problem that can be solved with oauth2. Oauth2 is widely used as a mechanism to give web applications developers access to users data at Google/Facebook/GitHub directly from the foreign services in a secure way.

What is Aouth2 
Oauth2 provides also a very elegant solution. The core components of oauth2 cooperates but they are loosely coupled to each other. In fact, they have no knowledge of each other. Once the system is in place, resource server modules that needs security can have almost  security for free.

  • Resource Owner - our users
  • Resource Server - This is any of module based spring boot that contains data of our users
  • Authorization Server - This is essentially the token endpoint. It could also any existing compliant oauth2 server or simply a spring based oauth2. It allows user to manage tokens that give access to resource servers. This is the central point for authorization where users give access to their resources and resource server validate theses tokens to build their security context
  • Client - This is any of module based spring boot that manage  data on the behalf of our users. Mobile apps, web apps, any program etc
How it works ? 

The user authenticates on a authorization service, which maps the user session to a token. The authentication is outside the scope of oauth2. Any further API call to the resource services must provide this token. The services are able to recognize the provided token and ask the authorization service, which authorities this token grants, and who is the owner of this resource.  

It is important to highlight that Oauth2 is not an authentication server and acts only as an authorization server by enforcing who can access to what. For that, it reuses the user identity obtained via authentication process as well as the application (client_id) who are consuming the resources on behalf the of user. 

With OAuth2 you can define, which application (web, mobile, desktop, additional website) can access which resources on the top of the user identity which tell us which user can access which data. 


JWT

Oauth2 doesn't solve all of our problems. OAuth2 as a protocol does not tell us how the token is looking like and where it is stored. Also, for each request against a resource micro service containing a token in the header, the service will perform another request to authorization server to check the token. That's not good enough.

To solve these two problems, we can use JWT or  JSON Web Token.  This token contains info about the OAuth client, optionally the user with its authorities and the granted scope that is serialized into JSON first, encoded with base64 and finally signed using cryptographic key. The result is called JSON Webtoken, which we use as an access token directly. This json token may be sign with public key, symmetric key or a shared key.

When this token is passed via HTTP header, the resource servers just have to take this JWT, verify it was really properly signed (meaning this token is coming from the authorization server), and instead of asking user info, deserializing the JSON content into a OAuth2Authentication, establishing a SecurityContext based on this.

Using JWT provides a simple way of transmitting tokens, containing the permissions and user data in the access token string. Since all the data is already inside, there neither is a need to maintain a token store, nor the resource servers must ask authorization for token checks. The security of the token is based on the underlying cryptographic primitive used to secured the tokens. So, using JWT makes OAuth2 available to micro services, without affecting the architectures scalability.


Work on progress.....