Skip to content

KubernetesJson use of SourceGenerationContext #1674

@IvanJosipovic

Description

@IvanJosipovic

Summary

The client currently uses reflection-based serialization in non-AOT library even though a SourceGenerationContext is already generated.
This adds unnecessary reflection-based overhead.
Additionally, SourceGenerationContext is private and prevents us chaining it with our own custom IJsonTypeInfoResolver.

Current Behavior

  1. Non-AOT library use reflection-based serialization.
  2. The generated SourceGenerationContext is not used by default, even though it's in the library.
  3. Callers cannot compose their own resolvers since the generated context is not exposed.

Expected Behavior

  1. Non-AOT builds should use the generated SourceGenerationContext by default and fall back to reflection-based if type is missing.
  2. SourceGenerationContext should be public so that we can KubernetesJson.AddJsonOptions and append our own IJsonTypeInfoResolver for our CRDs.

Rationale

Proposed Changes

  1. Initialize the client’s default JsonSerializerOptions with the generated context:
     public static class KubernetesJson
     {
         private static readonly JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions
         {
             #if !K8S_AOT
             TypeInfoResolver = JsonTypeInfoResolver.Combine(SourceGenerationContext.Default, new DefaultJsonTypeInfoResolver()) // Uses Source Generated IJsonTypeInfoResolver when available and falls back to reflection
             #else
             TypeInfoResolver = SourceGenerationContext.Default // Uses Source Generated IJsonTypeInfoResolver
             #endif
         };
    }
  2. Make SourceGenerationContext public
    This allows us to use KubernetesJson.AddJsonOptions and chain our own custom Source Generated IJsonTypeInfoResolver
      KubernetesJson.AddJsonOptions(x =>
      {
          x.TypeInfoResolver = JsonTypeInfoResolver.Combine(SourceGenerationContext.Default, MyCRDSourceGenerationContext.Default, new DefaultJsonTypeInfoResolver());
      });
  3. Remove src/KubernetesClient.Aot/KubernetesJson.cs as it is now redundant.

Happy to make this PR.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions