Posts

Showing posts from May, 2024

Kubevela FAQ - how do you inject env and secrets into your application?

To inject env or secret you need to make use of trait using a type call init-container. https://kubevela.io/docs/end-user/traits/references/#init-container apiVersion : core.oam.dev/v1beta1 kind : Application metadata :   name : simple-vela-app spec :   components :     - name : express-server-1       type : webservice       properties :         image : oamdev/hello-world         ports :          - port : 8000             expose : true         cpu : "1"         memory : "120M"       traits :         - type : init-container           properties :               name : express-server-trait               image : oamdev/hello-world               cm...

kubevela - port must be expose unless you're running some sort of batch job.

Image
 If you're hosting your webapi then you need to expose it.  By default port are not exposed. If you don't have these settings, that means port 8000 is not accessible.  

kubevela - how do you scale your app

Image
  The following are sample configuration and abit of description of how to scale your app. The red indicates resource to start your application with.  Yellow means start running the pod with 1 replica (manual scaling). Green indicates we would like to scale between 1-10 when cpu utilization hit 60 percent.

Using kubectl to quickly spin up a pod to run shell command

Using kubectl to quickly run a terminal on a namespace.  kubectl run my-shell --rm -i --tty --image ubuntu -- bash

kubevela installation

Image
First download vela using  powershell -Command "iwr -useb https://kubevela.io/script/install.ps1 | iex" Please ensure you install vela 1.9.9 and above. This version would allow you to work with k8s 1.29.  Run the following to install vela install To turn on vela UX vela addon enable velaux: The default username is admin and password is  VelaUX12345. Deploying first application  vela up -f https://kubevela.net/example/applications/first-app.yaml Check on the status  vela status first-vela-app If you would like to use the server, try vela port-forward first-vela-app 8000:8000 Resuming application vela workflow resume first-vela-app Once you have deployed it, your apps would look like this. Introducing Kubevela component These are basically the types of component supported - webservice -  long-running, scalable, containerized services that have a stable network endpoint to receive external network traffic from customers. -  cronjob - scheduled task that r...

kubevela - where can you find various definitions like trait - scaler?

 Would you like to know what and how you can configure the traits in kubevela?  You can simply go to the following link. Component Definition Trait Definition Policy Definition Workflow Step Definition

aks best practices link

  We have some good best practices for AKS. Please visit the following link below for more information. https://learn.microsoft.com/en-us/azure/aks/best-practices

Krustlet no longer being maintained anymore

apollo federation example resolve subgraphs types

For this example, we have a book and a bookreview. Book is hosted in location subgraph and bookreview is in review subgraph.  We would query book and it will automatically returns bookreview as well. As mentioned above, bookreview is automatically resolved and does not require boiler code in book subgraph.  Book subgraph. It has hardcoded book value and book review has only an id number tied to it.  import { ApolloServer } from '@apollo/server' ; import { startStandaloneServer } from '@apollo/server/standalone' import gql from 'graphql-tag' ; import { buildSubgraphSchema } from '@apollo/subgraph' ; const books = [   {     id : "1" ,     title : 'The Awakening' ,     author : 'Kate Chopin' ,     reviews : { id : "1" }   },   {     id : "2" ,     title : 'City of Glass' ,     author : 'Paul Auster' ,     reviews : { id : "2" }   },   {   ...

oauth best pratices

  you can find the best practices for oauth here. https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#name-protecting-redirect-based-f

git pushing code from a branch to main branch in another repository

  Let's say i created a new repository called supergraph-apollo-example-resolve-across-subgraph and i wanted to push my branch changes from a separate respository to main branch in this repository  Command to use  git remote add origin-subgraph-cross  https://github.com/mitzenjeremywoo/supergraph-apollo-example-resolve-across-subgraph.git   git push -u origin-subgraph-cross feat/subgraph-entity-references

A project which specifies SQL Server 2022 or Azure SQL Database Managed Instance as the target platform cannot be published to Microsoft Azure SQL Database v12.

Image
 Bump into this error while trying to setup my database project. Solution pretty simple, all we need to do is configure the "target platform" for our database - as shown in the diagram below:

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20

Encounter this issue when running autorest (that uses nodejs).  I am using node version:  v18.20.2 After i revert to use node v18.12.0, then i was able to get my app to run without this error. Since i am working with Azure devops yaml, i was able to use the following to resolve my issue.  - task : NodeTool@0   inputs :     versionSource : 'spec'     versionSpec : '18.18.0'

Apollo federation schema version

You can get the valid and latest version of apollo federation by going into the following url  https://www.apollographql.com/docs/federation/federation-versions/  

apollo router - running customize settings from a configuration file

  To run your router from a configuration file, you only have to use the followings router --dev --supergraph supergraph.graphql --config router.yaml From a kubernetes  https://github.com/apollographql/supergraph-demo-fed2/tree/main/supergraph/router-no-code

tsc build issue file is entry point of type library specified here.

 Getting this error today and then found out that i literally have to run "npm install" to get this working again. 

Strawberry shake - Exec(1,1) - All operation must be named

 If you have a query with name then you will get this error during dotnet build. For example,  query {    <--- missing name     book {     title    } } When you change it  this below, then you will not get a compilation error. Noticed we have appended query with GetBook. query GetBook {    book {     title    } }

graphql strawberry shake console app sample

My sample code for using strawberry shake to connect to a graphql service https://github.com/mitzenjeremywoo/graphl-client-strawberry-shake Some important things to note:  - graphqlrc.json  - schema.graphql - schema.extensions.graphql  - *.graphql - In the example, the filename is not important but having GetSession query in important as the code make use of the field return in the query.  As shown in the example here

error: src refspec main does not match any - probably the silly mistake that one can bump into

 If you hit this error, all you need to do is add or commit your code into git. 😅

package-lock.json when it is corrupted.

We can use the following command to re-genearted package-lock.json  npm i --package-lock-only  

refit http logging example

This is based off this blog .  I added some a minimal api version of it. You can check it out here .  Some of the pitfalls that I encounter are documented in the code for example,  Trying to setup my HttpMessageHandler that work for me. //// Adding our new handler here refitClientBuilder . AddHttpMessageHandler ( serviceProvider   = > new HttpLoggingHandler ( serviceProvider . GetRequiredService < ILogger < HttpLoggingHandler >>())); refitClientBuilder . Services . AddSingleton < HttpLoggingHandler >(); // doésn't work for me //refitClientBuilder.AddHttpMessageHandler<HttpLoggingHandler>(); Using the injected service version of it app . MapGet ( "/hello" , async ( IRandomUserAPI client ) => {     // no don't try this - use DI instead     //var randomClient = RestService.For<IRandomUserAPI>("https://randomuser.me");             var result = await client . GetUser ();   ...

aspnet core setting your webapi to listen on certain port

  You can use the following configuration to set you up quickly.   "Kestrel": {    "EndPoints": {      "Http": {        "Url": "http://localhost:4200"      }    }  }

refit - unable to find AddRefitClient extension

  To resolve this please add package run this from the command line dotnet add package Refit.HttpClientFactory --version 7.0.0

setting mitmproxy options

You can configure mitmproxy settings by using the following example  mitmproxy --set ssl_insecure=true  For a more complete list of options please refer to the link here .

AddJwtBearer understanding its purpose

The purpose of using AddJwtBearer is to secure your API endpoint (the ones decorated with Authorization attribute) and setting those constraints for example audience must have certain value before it can access your API.  In example configuration below, we only allow JWT token with audience "https://kepungapp.auth0.com/api/v2/" access. All other request will get 401.  You need to setup options.Authority and it must be a valid token issuer. builder . Services . AddAuthentication ()               . AddJwtBearer ( options =>         {                     options . Audience = "https://kepungapp.auth0.com/api/v2/" ;             options . Authority = "https://kepungapp.auth0.com/" ;                       //options.RequireHttpsMetadata = false;         }); If you run th...

aspnet core AddJwtBearer unable to find extension method

This might be abit too easy but sometimes it happens and then we need a proper solution. So just posting for so it can be helpful. If you trying to do something like  builder.Services.AddAuthentication() .AddCookie(options => { options.LoginPath = "/Account/Unauthorized/" ; options.AccessDeniedPath = "/Account/Forbidden/" ; }) .AddJwtBearer(options => { options.Audience = "http://localhost:5001/" ; options.Authority = "http://localhost:5000/" ; }); But getting unable to reference AddJwtBearer, just do this  dotnet add package  Microsoft.AspNetCore.Authentication.JwtBearer

hotchoc mongodb example code to add update and delete from a collection.

I have an simple example to add, update and remove mongodb using hotchoc graphql.   https://github.com/mitzenjeremywoo/hotchoc-graphql-db

hotchoc IMongoCollection returns only 1 record because of UseFirstOrDefaultAttribute

Figure i post the intention out before someone think it is a different issues. After some copy and paste job, I had this attribute in my graphql query method - which literally would return only 1 row or default eventhough I have many records in my collections. 

TypeLoadException: Could not load type 'Microsoft.IdentityModel.Json.JsonConvert' from assembly 'Microsoft.IdentityModel.Tokens, Version=7.0.3.0

Was getting this error, trying to add authentication feature into my app. Due to the assembly issues, I had to use the following assembly versions to make it work. 1st attempt <PackageReference Include="Microsoft.AspNetCore. Authentication.OpenIdConnect" Version="7.0.5" /> <PackageReference Include="Microsoft.AspNetCore. OpenApi" Version="7.0.5" /> <PackageReference Include="Swashbuckle. AspNetCore" Version="6.4.0" /> <PackageReference Include="System.IdentityModel. Tokens.Jwt" Version="7.0.3" /> 2nd attempt (more recent version of the assemblies)   <PackageReference Include="Microsoft.AspNetCore. Authentication.OpenIdConnect" Version="8.0.4" /> <PackageReference Include="Microsoft.AspNetCore. OpenApi" Version="7.0.5" /> <PackageReference Include="Swashbuckle. AspNetCore" Version="6.4.0" /> <PackageRefer...

hotchoc graphlq setting paging nation defaults programmatically

  Use the following code to configure your paginations sizes: public class Startup {     public void ConfigureServices ( IServiceCollection services )     {         services             . AddGraphQLServer ()             . SetPagingOptions ( new PagingOptions             {                 MaxPageSize = 100             });     } }

Mongodb - Element '_id' does not match any field or property of class -

  Getting this error when trying to query from my mongodb collection.  Element '_id' does not match any field or property of class.  Since I still wanted to work with the extra field _id, i would want to include additional field in there. public class Restaurant {     [ BsonId ]     public MongoDB . Bson . ObjectId _id { get ; set ; }       public string borough { get ; set ; }     public string cuisine { get ; set ; } } Sometimes you might want to consider ignoring additional field.  [ BsonIgnoreExtraElements ] public class Restaurant {     [ BsonId ]     public MongoDB . Bson . ObjectId _id { get ; set ; }       public string borough { get ; set ; }     public string cuisine { get ; set ; } }

Mongodb - Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1

 As stated in the stackoverflow, there could be a number of reason for this - but for my case, i ensure that the connection credential (username/password) is correct. 

postgres - when table size takes up more and more space

Some quick command that can be helpful to clear off some of the table spaces. -- Step 2. Check Table Size SELECT pg_size_pretty(   pg_total_relation_size( 'your-table-name' ) ) as table_size; SELECT   schemaname,   relname,   n_dead_tup FROM pg_catalog.pg_stat_all_tables WHERE relname = 'your-table-name' ; -- before autovacuum SELECT   schemaname,   relname,   n_dead_tup FROM pg_catalog.pg_stat_all_tables --- run vaccum vacuum your - table - name -- after autovacuum SELECT   schemaname,   relname,   n_dead_tup FROM pg_catalog.pg_stat_all_tables

graphql hotchoc using ResolveWith

  Using resolveWith might be a good use-case for you. You can use it with the following code example,  Then to run your query  query {     foo ( arg : "" )   }

hotchoc - supporting multiple object for resolving your object in graphql

Let's say you need to organize your code and instead of placing all the query method into a single object like you can do with AddQueryType<> in hotchoc graphql, you can place this into multiple object for easy maintenance.  For the rest of your classes you can have the followings   That's it!   

AKS best practices

To get all the best practices for AKS, please check out https://learn.microsoft.com/en-us/azure/aks/best-practices

AKS - Service connector setup and wiring up that to your app

To setup your service connector in Azure AKS Cluster https://learn.microsoft.com/en-us/azure/service-connector/quickstart-portal-aks-connection?tabs=UMI One you have your connection registered, it is time to used that with your applications https://learn.microsoft.com/en-us/azure/service-connector/tutorial-python-aks-storage-workload-identity  

AKS updates and other new features

One of the best place to get more additional info about AKS new features can be found here. https://github.com/Azure/AKS/tree/master Then you branch out to the followings interesting link - AKS Roadmap (https://github.com/Azure/AKS/projects/1) - Features (https://github.com/Azure/AKS/projects/1#column-5273286)

keycloak token exchange - sample request - internal to internal client

Image
  Ensure you have keycloak token-exchange feature turned on docker run --name mykeycloak -v c:\work\keycloak\conf:/opt/keycloak/conf -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KC_METRICS_ENABLED=true -e KC_HEALTH_ENABLED=true -e KC_FEATURES="token-exchange, admin-fine-grained-authz" -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:24.0.3 start-dev --cache-config-file=cache.xml Simply using token-exchange might not be adequate. To get started with token exchange, we need to set up 2 internal clients.  1. client to generate the token - Client will be called "selfservice_bff_unprivledge". This is the source of the token. This client is just a confidential client.  2. Client that will allow token-exchange to happen. You need to configure this client here - to say I am going to allow token exchange here with client "selfservice_bff_unprivledge". Create a confidential client called selfservice_bff_privledge" To setup token exchange, follow these step...