Thursday 28 February 2019

Lyon, Part-Dieu

Lyon, one of the most beautiful European cities, and probably the most underrated. The city enjoys an idyllic geographic setting, and for centuries those fortunate enough to inhabit it have tried to live up to nature gifting it with majestic works of architecture. This process continues to these days, and over the last years the city has gained some really beautiful pieces of modern architecture (from the whole neighbourhood of "Confluences" to the stylish "Incity" skyscrapper).

However, my initial impression when I first set foot in Lyon, back in 2014, was not so good. I reached the city by train stopping at La Part-Dieu station. At that time most of the French train stations that I knew were beautiful examples of classic, imposing constructions that bring you back more than 1 century in time (Paris Gare du Nord and Saint Lazare, Bordeaux St Jean, Toulouse Matabiau, Marseille Saint Charles...), so when I found myself in Lyon's main train station I felt deeply disappointed. A train station from the 70's lacking any remarkable element, and with its main entrance placed in a rather ugly square. As you walk away a few meters you come across the "Tour Oxygene" and the "Tour Part-Dieu", that while not particularly appealing to me, at least give you a first taste of modern architecture that is not so common in such a conservative (in urban terms) country as France (yes, sure you have amazing modern architecture in France, but the "average French" looks at modern constructions with such a senseless distaste...). A couple of years later the "Tour Incity" brought the city with full rights into the modern world (yes, I absolutely love this skyscrapper, even more than the Iberdrola Tower in Bilbao and at par with the Tour CMA-CGM in Marseille) and I also began to feel more and more at ease with the old office buildings that fill the area.

Anyway, the impression when you get to the station, has continued to be quite poor for such an amazing city. This said, when in my last stay in Lyon in early January I found out about the huge remodeling process that La Part-Dieu (not just the station, but the whole neighbourhood) is undergoing I felt pretty delighted. The ugly buildings that surround the main entrance to the station are going to be demolished, one of them being replaced by the Tour To-Lyon. The old EDF tower is being reconstructed and vertically expanded, metamorphosing into the Tour Silex 2 (I have to admit that the project is not too exciting, but it's one more step in the right direction). There are many more potential projects, and though many of them will not materialize, Lyon is the French city (along with Paris) with more chances to allow new innovative and modern architectural landmarks to emerge. The population here appears to have a more open attitude and seems to be aware that they live in a European big city and not in a little village, and the fucking "neighbours associations" so present everywhere in France (particularly in Toulouse) that try to stop any "urban action" (from new metro lines to buildings of more than 5 floors) don't seem to be so powerful and bothering. Also, Lyon (contrary to Toulouse, Rennes, Nantes...) is fortunate not to be infected by thousands of far-left antiprogress "militants" that boycott (physically and violently if necessary) any interesting urban project accusing it of being a "capitalist attack" perpetrated by the "elites" against the "people" and the environment...

You can learn more about what is being done and will be done in the area, just pay a visit here.

Wednesday 20 February 2019

Modifiable Proxy

There's something in ES6 proxies that I see as a downside when used for intercepting method calls if we compare them to mechanisms like the beautiful invokeMethod provided by Groovy or directly monkeypatching the object replacing its funtions by new ones that run the additional code and then call the original (we can do this in JavaScript or Python). The downside is when you already have an object referenced from different places. Creating a proxy around it won't magically point those references to the new object, so basically you have to decide that you are going to use a proxy to that object before passing it to any consumer.

Most times this is not a big deal. We work with shortlived objects and we won't be deciding over their lifetime if we want to proxy them or not. Well, this is not so true. For example the DI mechanism in Angular is by default injecting as services a single instance, so they will be alive for way too long. Thinking a bit about it I've come up with an alternative. If there are chances that we could want to proxy the object in the future, why not proxying it now with a "do nothing" proxy, and modify this proxy in the future to "do something".

Exploring this option I read somewhere about modifying the handler object associated to the proxy. The idea seemed a bit odd to me cause I was expecting that the Proxy constructor would use the handler object in a similar way as an options object. I thought the different traps in the handler object would get assigned to some internal structures in the proxy, and basically, the handler itself would be of no more use, but I was pretty wrong. If you keep one reference to the handler provided to your proxy and replace one of the traps in it, the proxy will use the new trap. Let's see an example.


class Person{
 constructor(name){
  this.name = name;
 }
 
 sayHi(){
  return "Hello I'm " + this.name;
 } 
}
 
let p1 = new Person("Francois");
console.log(p1.sayHi());

let loggingHandler = {
  get: function(target, property, receiver) {
 let it = target[property];
 if (typeof it != "function"){
  return it;
 }
 else{
  return function(){
   console.log(property + " started");
   return it.call(this, ...arguments);
  }
 }
  }
  
  // resetGetTrap: function(){
   // this.get = function(target, property, receiver) {
  // return target[property];
   // }
  // }
};

console.log("----------------------");
console.log("Modifying handler test");
let proxiedP1 = new Proxy(p1, loggingHandler);
console.log("- Operations with proxiedP1");
console.log(proxiedP1.sayHi());

//let's change the "get" trap

loggingHandler.get = function(target, property, receiver) {
 let it = target[property];
 if (typeof it != "function"){
  return it;
 }
 else{
  return function(){
   console.log(property + " STARTED!!!");
   return it.call(this, ...arguments);
  }
 }
  }
  

console.log("after modifying handler");
console.log(proxiedP1.sayHi());

// - Operations with proxiedP1
// sayHi started
// Hello I'm Francois
// after modifying handler
// sayHi STARTED!!!
// Hello I'm Francois

As you can see in the output, replacing the trap in the handler affects the existing proxy, pretty nice... The thing is that having to store a reference to the handler is a bit of a pain, the nice way would be that the proxy itself provided a mechanism to change the trap. Well, that turns to be rather simple. I've written a factory function (modifiableProxyFactory) that creates a proxy with a get trap that when intercepting a "setGetTrap" access will interpret it as a command to change the existing get trap logic. For that it captures the real trap code in a closure. Let's see:

function modifiableProxyFactory(target){
 //initialize the proxy with a "transparent" trap
 let coreGetTrapFunc = (target, property, receiver) => target[property];
 let handler = {
  //the "get trap" checks if we want to set the trap, otherwise it invokes the existing trap
  get: function(target, property, receiver){
   if (property === "setGetTrap"){
    console.log("setting a new get trap!");
    return function(getTrap){
     coreGetTrapFunc = getTrap;
    };
   }
   else{
    return coreGetTrapFunc(target, property, receiver);
   }
  }
 };
 return new Proxy(target, handler);
}

let p2 = new Person("Emmanuel");
console.log(p2.sayHi());

let proxiedP2 = modifiableProxyFactory(p2);
console.log("\n- After creating 'empty' proxiedP2");
console.log(proxiedP2.sayHi() + "\n");


//------------------------------------
proxiedP2.setGetTrap(function(target, property, receiver){
 let it = target[property];
 if (typeof it != "function"){
  return it;
 }
 else{
  return function(){
   console.log(property + " called");
   return it.call(this, ...arguments);
  }
 }
});

console.log("\n- After reassigning get trap");
console.log(proxiedP2.sayHi() + "\n");

//-- output:

// Hello I'm Emmanuel

// - After creating 'empty' proxiedP2
// Hello I'm Emmanuel

// setting a new get trap!

// - After reassigning get trap
// sayHi called
// Hello I'm Emmanuel


I've uploaded it as a gist here

Friday 15 February 2019

Async Main

Since C# 7.1 we can declare the main method of our application as async. This means that it can contain statements with the await keyword. So now we can write code like this:

static async Task Main(string[] args)
{
	Console.WriteLine("Main Started");
	var post = await GetPostAsync();
	Console.WriteLine(post);
}

In the past, we would have needed to do something like this:

static void Main(string[] args)
{
	Console.WriteLine("Main Started");
	var post = GetPostAsync().Result;
	Console.WriteLine(post);
}

The new async Main can look a bit like magic. We know that when the execution flow comes across an await it jumps out of that method, and the remaining of the method will be continued when the await action is complete. The thing is that if Main itself is async, where is the flow jumping out to?

Well, it seems that the compiler creates an additional method that becomes the real entry point to the application. It invokes the async Main and waits for it to complete, basically doing the same we were doing before C# 7.1. I've not checked it myself, but others have decompiled and posted about it.

[SpecialName]
private static void Main(string[] args)
{
	Program.Main(args).GetAwaiter().GetResult();
}

Thinking a bit more about it I've realised that there's a slight different between the "old, manual way" and the "new, compiler managed way", the thread that ends up running the continuation code. Let's see an example:

static async Task GetPost()
{
	Console.WriteLine("GetPost started - Thread: " + Thread.CurrentThread.ManagedThreadId);
	await Task.Delay(1000);
	Console.WriteLine("GetPost after first part - Thread: " + Thread.CurrentThread.ManagedThreadId);
	await Task.Delay(1000);
	Console.WriteLine("GetPost after second part - Thread: " + Thread.CurrentThread.ManagedThreadId);
	return "Post content";
}

If we invoke the above code "the old way", without async Main, all the code in the Main method is run by the same thread (it get's stopped in the .Result property access (same as calling .Wait()), and then continues)

static void Main(string[] args)
{
	Console.WriteLine("Main Started - Thread: " + Thread.CurrentThread.ManagedThreadId);
	var post = GetPost().Result;
	Console.WriteLine("Main after GetPost - Thread: " + Thread.CurrentThread.ManagedThreadId);
	Console.WriteLine("post: " + post);
}


// Main Started - Thread: 1
// GetPost started - Thread: 1
// GetPost after first part - Thread: 4
// GetPost after second part - Thread: 4
// Main after GetPost - Thread: 1
// post: Post content

However, if we invoke the same method from an "async Main", the second part of the Main, the one after await is run by a thread different from the one that started the Main (notice that the starting thread is blocked in the "hidden" GetAwaiter().GetResult()).

static async Task Main(string[] args)
{
	Console.WriteLine("Main Started - Thread: " + Thread.CurrentThread.ManagedThreadId);
	var post = await GetPost();
	Console.WriteLine("Main after GetPost - Thread: " + Thread.CurrentThread.ManagedThreadId);
	Console.WriteLine("post: " + post);
}
//Main Started - Thread: 1
//GetPost started - Thread: 1
//GetPost after first part - Thread: 4
//GetPost after second part - Thread: 4
//Main after GetPost - Thread: 4
//post: Post content	
		

For the most part whether that code runs in one thread or another is of no particular concern, but I can think of at least one case where it matters, when impersonation is being used.

Tuesday 5 February 2019

Sync/Async, Push/Pull

Time ago I wrote about Enumerables and async in C#. C# 8 will bring us this gift, same as last versions of JavaScript. In C# this feature made up by the IAsyncEnumerable/IAsyncEnumerator and the new await foreach loop has been called Async Streams. In JavaScript the feature is called async iterator. The Async Stream naming used in C# got mixed in my head with other terms like push streams, pull streams, synchronous, asynchronous, so I tried to clean up my mind a bit thinking about examples of each case. I'll use the term "stream" in a generic way, not directly associated to C# or Java stream classes. I could just have use the term "sequence".

  • Synchronous Pull Streams. Just a conventional enumeration/iteration. An object that can provide several items. We can iterate it by requesting an item and synchronously wait for it. IEnumerable/IEnumerator, [symbol.iterator]... you know.
  • Asynchronous Pull Streams. Just the new C#/JavaScript feature I was talking above. In each iteration we request an item and we asynchronously wait for it.
  • Asynchronous Push Streams. An Observable is the perfect example. We subscribe to it and it will push data to us in an asynchronous way.
  • Synchronous Push Streams. This is not so obvious, but Observables also fit here. While we normally think of observables as a data source providing data over a certain period, an Observable can also be synchronous. We subscribe to it and immediatelly it pushes to us all its items. Do you want an example?
console.log("starting"); 
of("Celine", "Francois").subscribe(nm => console.log("Hi " + nm));
console.log("finishing");

//output:
//starting
//Hi Celine
//Hi Francois
//finishing