Angular DI: Getting to know the Ivy NodeInjector

Angular DI: Getting to know the Ivy NodeInjectorAlexey ZuevBlockedUnblockFollowFollowingJan 28In this article, we’re going to examine a new Angular NodeInjector which heavily uses a bloom filter to retrieve a token.

We’ll take a look at:How the NodeInjector looks likeHow Angular builds bloom filter for NodeInjector and when we can catch false positive valuesWhat’s the resolution algorithm for resolving dependencies in NodeInjectorIntroductionThe NodeInjector is one of the two new types(another one is R3Injector) of Angular injectors introduced by Ivy renderer.

We will be switched to them as soon as Ivy renderer is landed.

The NodeInjector is going to replace the current Element injector(Injector_ in the picture above) and reduce memory pressure in Angular application by using bloom filter.

Let’s first take a look at a simple application I’ll use along the way:The app is pretty simple.

We have root AppComponent that contains two nested div elements.

Also, there are two directives which are applied to those elements.

What we’re going to understand is how Angular will be able to get root AppComponent instance in DirB directive.

Now that we have our goal defined, let’s get started.

View as a template representationI think you’re familiar with the concept of the view object in Angular.

In simple words, it is some internal object that represents an Angular template.

We know that Angular builds a tree of views which always starts with a fake root View that contains only one root element.

This is how it works in View Engine.

The same can be applied to the upcoming Ivy engine.

To keep internal data Angular Ivy uses LView and TView.

data arrays.

The LView array contains data describing a specific template and in TView.

data Angular keeps the information that is shared across templates.

Also, Angular Ivy renderer stores the injection information for the node in view data.

In other words, it allocates slots in those LView and TView.

data arrays.

These slots represent two bloom filters: cumulative and template.

One view can have as many bloom filters as many injectors are created for nodes which are located on this view.

Here’s a visualization of what it looks like:There are a few takeaways from this picture above:Ivy view is represented by LView and TView.

data arrays that start from the header(17 slots).

This header contains the reference to the parent injector at index 10.

Here’s where Angular resolution algorithm is switched to Module Injector.

The LView and TView.

data arrays can contain lots of bloom filters 8 slots long ([n, n + 7] indices).

Their number is directly proportional to the number of nodes for which the injector is created.

Each bloom filter has a pointer to the parent bloom filter in the “packed” parentLocation slot (n + 8 index).

By “packed” I meant that this slot’s value contains not only parent injector index but can also contain ViewOffsetShift.

The packing and unpacking is a common use of the bitwise operators when we encode several values in one int.

Angular stores all tokens in TView.

data and instances in LView so that we can retrieve all providers looking at the view.

Let’s get back to our application and see how many views we have there:That’s quite simple.

We have root view and one child AppComponent view.

In the root view, we see one pair(cumulative in LView and template in TView.

data) of bloom filters.

The AppComponent view keeps two pairs of bloom filters: one for div[dirA] element(index 21) and other for div[dirB] element(index 31).

Now, that we have some knowledge of what an Angular Ivy view is, let's move on to bloom filter.

Cumulative and template bloom filtersIf you are not familiar with bloom filter you might be interested in these great articles: Probabilistic Data structures: Bloom filter and Bloom Filters by ExampleIn Angular Ivy we have a quite interesting implementation of bloom filter.

Template bloom filter is a filter that keeps information about the current node’s tokens and which can be shared in TView.

Let’s see how it is built.

As mentioned earlier “Bloom Filters by Example” article states:The base data structure of a Bloom filter is a Bit Vector.

So what’s the bit vector in Angular bloom filter?Ivy defines bloom size equal to 256 so that we have a vector in 256 bits which are divided into 8 parts.

n .

n + 700000000000000000000000000000000 .

00000000000000000000000000000000____________32 bits___________/ ____________32 bits___________/How Angular hashes elements in that filter?First, Angular generates(if it is not defined yet) a unique ID for token via incrementing integer value and puts it to static __NG_ELEMENT_ID__ property:Note: our AppComponent got 0 id since the token generation starts with 0 and AppComponent is the first directive which Angular adds to the injection system.

Then, it takes that number and fits it to the bloom size through bitwise AND(&) operator so that the result is always between 0–255.

const BLOOM_SIZE = 256;const BLOOM_MASK = BLOOM_SIZE – 1; // 255/* it's like a remainder operator* so that all unique ids are modulo-ed* into a number between 0-255*/const bloomBit = id & BLOOM_MASK; 0 & 255 // 01 & 255 // 1255 & 255 // 255256 & 255 // 0257 & 255 // 11000 & 255 // 232Finally, Ivy creates a mask using that bloomBit:const mask = 1 << bloomBit;and sets that mask in one of 8 buckets depending on bloomBit:So, for all possible Ids, that are modulo-ed into a number between 0–255, we always get the following structure of bloom filter: Ids 0-31 1 bucket 00000000000000000000000000000000 ____________32 bits___________/ Ids 32-63 2 bucket 00000000000000000000000000000000 .

Ids 224 – 255 8 bucket 00000000000000000000000000000000 Okay, a lot is going here.

Let me rephrase.

Having the directive like:@Directive({.

})class MyDirective { static __NG_ELEMENT_ID__ = 1;}will result in the following bloom filter:const bloomBit = 1 % 255 // 1const mask = 1 << bloomBit; 1 << 1 // 22.

toString(2) // 10 1 bucket 00000000000000000000000000000010.

8 bucket 00000000000000000000000000000000 How does Ivy check whether a given Id is in the set or not?Ivy creates the same mask that targets the specific bit and simple checks that mask with dedicated bucket.

const bloomBit = 1 % 255 // 1const mask = 1 << bloomBit; 1 << 1 // 22.

toString(2) // 10 1 bucket2 & 0b000000000000000000000000000000100b00000000000000000000000000000010 &0b00000000000000000000000000000010 ||0b00000000000000000000000000000010 = 2 = trueNow, let’s talk about cumulative bloom.

Cumulative bloom filter is a filter that stores information about the current node’s tokens as well as the tokens of its ancestor nodes.

So, basically, it merges the parent’s bloom filter and its own cumulative bloom.

Using this filter we can give a quick answer if there is a token in parent injectors without the need for traversing all parent injectors.

What’s the NodeInjector?In simple words, it’s an injector which belongs to a node.

You can think of it the way you would think of any other injector.

It is like a container that is used to retrieve object instances as defined by the provider.

But I would say it’s a special kind of containers.

Where does this container keep those providers?First, I would look at its definition in source code:Comparing it to R3Injector:we can say that NodeInjector doesn’t have any kind of key-value store which is commonly used to create injector.

The NodeInjector is an object that has references to TNode and LView objects.

The TNode might be any kind of object: element, ng-template, ng-container.

The NodeInjector gets the required provider by looking at the data contained in TNode and LView objects.

And here is where our bloom filters from the previous chapter come into play.

Angular creates an injectorIndex property on TNode in order to know where dedicated to this node bloom filter is located.

Also, as we learned before after each bloom filter Angular also stores parentLocation pointer in LView array so that we can walk through all parent injectors.

So we can conclude that each NodeInjector is saved in 9 contiguous slots in LView and 9 contiguous slots in TView.

data.

When Angular creates NodeInjector on a node?You may think that Angular does it for every node it creates.

But it is not true.

There are a few cases when it happens:Root component always creates NodeInjector on root view.

Angular creates NodeInjector on any tag that matches Angular component or any tag on which we’re applying a directive.

Providers and viewproviders defined on Component/Directive also create NodeInjector if it has not been created yet.

So, every time we have a tag with directive applied(it might be component or directive) we create NodeInjector on that TNode.

That’s why all directives are known by node injector.

Now, its time to learn how NodeInjector resolves dependencies.

Resolution algorithmAs we have already seen earlier, the NodeInjector’s get method looks like:So, the getOrCreateInjectable method is the main entry point.

There are lots of code, but let me break it down for you.

Imagine that we’re calling injector.

get(SomeClass)Angular looks for a hash in SomeClass.

__NG_ELEMENT_ID__ static property.

If that hash is equal -1 then it is a special case and we’ll get NodeInjector instance.

If that hash is a factory function then we have another special case where we should initialize object by calling that function.

Angular defines factory function in __NG_ELEMENT_ID__ static property for the following special objects: ChangeDetectorRef, ElementRef, TemplateRef, ViewContainerRef, Renderer2.

An interesting thing about these objects is that they are not memoized.

For example, injector.

get(ChangeDetectorRef) !== injector.

get(ChangeDetectorRef)4.

If that hash is a number then we’re:getting injectorIndex from TNode.

looking at template bloom filter(TView.

data[injectorIndex])If bloom filter gives us true then we search for SomeClass token.

(We have tNode.

providerIndexes so we can find desired token)If it gives us false then we look at the cumulative bloom.

If it gives us true we continue on traversing otherwise we are switched to ModuleInjector.

NodeInjector resolution algorithmIt’s time to take a closer look at how we’re getting root AppComponent in our simple application:False positiveYou might be interested in cases when we can get an erroneous result from bloom filter, aka false positive.

Bloom has a size of 256 bits.

Once we crossed 255 ids we can catch false positive.

Let’s see it on the example:AppComponent has __NG_ELEMENT_ID__ defined to 0.

We also manually defined id 256 for DirA.

0 and 256 will give us the mask at the same index so we get positive false.

But it is safe to have such a false positive result since after searching the token directly on a view we will get null.

Summary: the more directives and services on those directives we have, the more false positive values we can get.

ConclusionFinally, we have come to end.

I hope now you have some basic understanding of how the Ivy NodeInjector works.

If you haven’t then I suggest you reading Angular source code.

And for sure you will discover lots of patterns and best practices there.

Additional ResourcesWhat you always wanted to know about Angular Dependency Injection treeIf you didn’t dive deep into angular dependency injection mechanism, your mental model should be that in angular…blog.

angularindepth.

com.

. More details

Leave a Reply