Getting word count from template files

Recently I had to get an approximate word count of an entire site for estimating translation time. To do this I processed the template files to get all the non-html tag/logic content using find and sed, then counted the words using wc.

# from views directory

# create .out files with HTML tags stripped
find . -name '*.html' -exec sh -c 'sed -e "s/<[^>]*>//g" $1 > $1.out' -- {} \;

# create .out.bout files with nunjucks/jinja2 tags stripped
find . -name '*.html.out' -exec sh -c 'sed -e "s/{[^}]*}//g" $1 > $1.bout' -- {} \;

# word count
find . -name '*.html.out.bout' | xargs wc -w

Links:

Session data is the manageable devil you know

devil-29973_640

Last year I wrote a bit of a rant post “Session data is evil” coming out of some projects which suffered from session related problems. Time and some experience trying to avoid sessions have softened my opinion, so I thought I would write a counter-point to that post.

It’s extremely hard to avoid state

People think in states. They naturally work incremently, adding a little here, editing/removing a little there, not in large atomic chunks. The means they don’t like large complex forms that require everything being entered/edited at once. They also expect little things that require state, remembering preferences and where they were in an application process. While it is possible to break down your application while avoiding state, it means increasing the complexity of your persistence and routing, adding complexity.

Session data is the most straight forward way to deal with these hidden requirements.

Dealing with sessions is a known problem

Sessions may be tricky, but there’s decades of experience dealing with them. Most web servers and frameworks have explicit tools and best practises for using them, supporting sticky sessions and external session state for multiple web servers.

Using sensible approaches it is entirely possible to scale and handle sessions correct.

Over engineering causes worse problems

If in an effort to remove sessions you add tons of persistence and routing complexity, you are just adding more code and places for things to go wrong. A simple session based approach is easier to maintain and understand than a over-complicated stateless one that is making explicit calls every request. It will work fine so long as you use session sensibly, encapsilate it, understand the limitations and how it will work in production conditions.

Large scale and PaaS applications may have to be much more careful, but there are still ways to work with sessions for them.

Conclusion

Don’t abandon session out of fear or fashion, it’s a simple and extremely common approach for managing state in a world that demands it, just don’t shove everything in there…

The symmetrical architecture trap

Often when thinking about topics to write about I hesitate, as in retrospect what I’m saying seems obvious. But it’s very common to fall into simple patterns when you are in the thick of a project, doing something which the flaws only become apparent later when early chaos is over and you can think clearly.

One of these traps is symmetrical application architecture, making two similar components in your solution use the same architecture, even when they have different requirements.

A common example of this is when a web application will have a public facing external site and a more secure internal site for administration. On the surface these two components have similarities, they both serve HTML and need to access/persist data, so you may initially use the same architecture for them.

Symmetric architecture diagram

However, you soon realise the external site needs to handle much more traffic than the internal, and it’s data requirements are different (higher read or write, only needing access to specific data). You can resolve this by scaling the architecture, but it’s clunky.

Symmetric architecture with external load diagram

Then you realise the internal site has more security and auditing requirements. You can resolve with implementation changes but it would be neater to include additional layers or services.

Symmetric architecture with internal audit security diagram

The symmetry of the architecture becomes a conceptual barrier to change, changing either one appears to be introducing more complexity but in reality the implementations are diverging anyway due to their different circumstances. Looking at them individually and at how they will be hosted on less abstract infrastructure diagrams can help. Could be your external and internal sites don’t need the same data store or layers, and changing them could save resources and simplify implementation.

Asymmetric architecture diagram

Embracing asymmetry in your architecture early can help you break out of this mindset and prevent you hitting problems later when your implementation work arounds start to creak.

Design – Minimalist principle of least privilege web application approach

principle-of-least-privilege-db-design-1

I used this design on a recent project and wanted to write up my thoughts.

This approach was taken as the project was a small scale web application with quick time scales. I’d previously worked on several projects which took a generic web-api-db pattern, even when there was no plan or ability to scale or separate the components out, so the implementation increased complexity for little gain. Also principle of least privilege had come up in some security reviews, database permissions not really being considered early on.

I wanted to see if I could cut out the API components, that added an additional layer of mainly boilerplate code, without resorting to a monolith design. This also reduced the complexity of the infrastructure and networking. Experience from looking at database permissions made me aware that users/roles/schemas permissions can be set very fine grained, providing assurances that connections can be locked down to specific tables/operations (e.g. SELECT/UPDATE only, no DELETE)

You could take this  further and go for full microservice split, with internal/external each having a separate worker and communicating via limited exposed API endpoints, but for this project that wasn’t really necessary and I was sick of designs dictated by patterns rather than needs.

Scenario

You have two applications:

  • external-web
    • Public site used by unauthenticated users and exposed to the internet
    • Allows users to submit application data to be processed, with a limited view of previously submitted application data
    • High risk, don’t want users to potentially view other users application data or change details
    • Higher usage than internal (public facing, unpredictable traffic)
  • internal-site
    • Internal site used by authenticated users and IP restricted
    • Allows users to process applications
    • Lower risk, but still don’t want users to be able to perform actions like deleting records or submitting applications
    • Low number of active users (small team)

Proposed solution:

  • Split the data stores, so external-web and internal-web have their own stores, with external-web only holding data as long as necessary
  • Use permissions to prevent each application from doing anything other than the minimum they need on their stores (principle of least privilege)
  • Use a worker application, not exposed or directly connected to either application, to move data between the two
  • Use either a special API or function to allow external-web to query historic data with limited access, so it cannot query the entire store

Thoughts on outcome

Pros

  • Simple and low number of components (moving parts that could go wrong)
  • Low infrastructure requirements
  • Still able to scale internal/external independently
  • Less code and complexity
  • Public facing site only has access to data in transit, not large amounts of long term data

Cons

  • Public facing application has access to database (even if limited to select/updates)
  • Unable to scale external/internal API independently from sites
  • Worker unable to scale independently of external/internal
  • Lose a lot of relational integrity from copying between stores if using relational stores

Links

Building and tagging container images in CI

docker-ci-tagging-anon

Been thinking a lot recently about how to manage versioning and deployment using Docker for a small scale containerised solution. It’s different from a traditional release pipeline as the build artifacts are the container images with the latest code and configuration, instead of the CI having a zip of the built application.

In a completely ideal containerised microservice solution all containers are loosely coupled and can be tested and built independently. Their CI configuration can be kept independent as well, with the CI and testing setup for the entire orchestrated solution taking the latest safe versions of the containers and performing integration/smoke tests against test/staging environments.

If your solution is smaller scale and the containers linked together, this is my proposed setup.

Build

Images should be built consistently, so dependencies should be resolved and fixed at point of build. This is done for node with npm shrinkwrap which generates a file fixing the npm install to specific dependency versions. This should be done as part of development each time package.json is updated, to ensure all developers as well as images use the exact same versions of packages.

On each commit to develop the image is built and tagged twice, once with “develop” to tag it as the latest version for develop branch code, and then with the version number in the git repo VERSION.md (“1.0.1”). You cannot currently build with multiple tags, but building images with same content/instructions does not duplicate image storage due to Docker image layers.

Tagging

The “develop” tagged image is used as the latest current version of the image to be deployed as part of automated builds to the Development environment, in the develop branch docker-compose.yml all referenced images will use that tag.

The version number tagged image, “1.0.1”, is used as a historic fixed version for traceability, so for specific releases the tagged master docker-compose.yml will reference specific versioned images. This means we have a store of built versioned images which can be deployed on demand to re-create and trace issues.

On each significant release, the latest version image will be pushed to the image repository with the tag “latest” (corresponding to the code in the master branch).

Managing data store changes in containers

docker-container-ci-data-migrations

When creating microservices it’s common to keep their persistence stores loosely coupled so that changes to one service do not affect others. Each service should manage it’s own concerns, be the owner of retrieving/updating it’s data and define how and where it gets it from.

When using a relational database for a store there is an additional problem that each release may require schema/data updates, a known problem of database migration (schema migration/database change management).

There a large number of tools for doing this; flyway, liquibaseDbUp. They allow you to define the schema/data for your service as a series of ordered migration scripts, which can be applied to your database regardless of it’s state as a fresh DB or existing one with production data.

When your container service needs a relational database with a specific schema and you are performing continuous delivery you will need to handle this problem. Traditionally this is handled separately from the service by CI, where a Jenkins/Teamcity task runs the database migration tool before the task to deploy the updated release code for the service. You will have similar problems with containers that require config changes to non-relational stores (redis/mongo etc.).

This is still possible in a containerised deployment, but has disadvantages. Your CI will need knowledge/connection to each containers data store, and run the task for each container with a store. As the number of containers increase this will add more and more complexity into your CI which will need to be aware of all their needs and release changes.

To prevent this from happening the responsibility of updating their persistence store should be on developer for the container itself, as part of the containers definition, code and orchestration details. This allows the developers to define what their persistence store is and how it should be updated each release, leaving CI only responsible for deploying the latest version of the containers.

node_modules/.bin/knex migrate:latest --env development

As an example of this I created a simple People API node application and container, which has a dependency on a mysql database with people data. Using Knex for database migration, the source defines the scripts necessary to setup the database or upgrade it to the latest version. The Dockerfile startup command waits for the database to be available then runs the migration before starting the Node application. The containers necessary for the solution and the dependency on mysql are defined and configured in the docker-compose.yml.

docker-compose up

For a web application example I created People Web node application, that wraps the API and displays the results as HTML. It has a docker-compose.yml that spins up containers for mysql, node-people-api (using the latest image pushed to Docker Hub) and itself. As node-people-api manages it’s own store inside the container node-people-web doesn’t need any knowledge of the migration scripts to setup the mysql database.

Links

Session data is evil

I’ve been working in ASP.MVC recently after working in Java for a long time. One of the things that struck me was the common use of session data in web application.

Now I know that people can and do use abuse sessions in Java, but the default routing and ease of access make using it more tempting in ASP.MVC. The standard routing convention of “/Controller/Action/:id” means you need to explicitly code to use RESTful paths that give you multiple IDs in URLs like “order/2/item/3” for non-trivial scenarios, and out of the box convenience methods like “TempData” seem to offer magical persistence between requests. These incentives combine to make using session data the path of least resistance in ASP.MVC.

1487ta

Any data stored in session is inherently unreliable and use of it makes load balancing and scaling your application much more difficult. Once you use it, each instance of your web application must be able to find the users session data to reliably handle requests. Since it’s now extremely common to use multiple instances even for small applications (irresponsible not to for disaster recovery and redundancy) you will need to think about this before you deploy into production.

It also adds hidden complexity to testing your application. Each endpoint which relies on state stored in session needs to be tested with that application state simulated. This means you have at least two places in your code defining and using the same semi-structured data, which makes your tests complex/fragile and your code harder to maintain.

Stelhi_Silk_Mill_Lanco_broken_windows

Once you make using session data part of your architecture it’s very hard to refactor and remove it. That little innocent use of TempData to store details from the last request will spread as Developers think “If it was ok there then it’s ok here…” and “one more can’t hurt” (the broken windows theory). Now your user flows in the web application rely on session stored details to go from screen A to B to C, and refactoring them means re-writing and testing a lot of the view/controller logic to replace the data held in session.

There are acceptable uses for session data in web application, authentication is the obivous one. What they have in common is having alternative flows to cope if session data is not found without breaking functionality.

If you have an over reliance of session in your application you are making a flakey, hard to scale and maintain application that will at best limp into production. At worst it will fall over and take your users data with it.

There are common patterns and methods to avoid needing session data, below are some links to help: