Patch fails with `error decoding patch: json: cannot unmarshal object into Go value of type []handlers.jsonPatchOp`
Describe the bug
I would like to patch a resource with a request body in JSON Merge Patch, RFC 7386 format. However, even if I specify the Content-Type application/merge-patch+json in a PromiseMiddlewareWrapper, add it into a ServerConfiguration and then use the configuration in the client method k8sApi.patchNamespacedPod({xxx}, configuration), the error still occurs:
ApiException [Error]: HTTP-Code: 400
Message: Unknown API Status Code!
Body: "{\"kind\":\"Status\",\"apiVersion\":\"v1\",\"metadata\":{},\"status\":\"Failure\",\"message\":\"error decoding patch: json: cannot unmarshal object into Go value of type []handlers.jsonPatchOp\",\"reason\":\"BadRequest\",\"code\":400}\n"
Headers: {"audit-id":"f2f1b40e-9d4a-49cf-af2b-989bed7de17e","cache-control":"no-cache, private","connection":"close","content-length":"211","content-type":"application/json","date":"Tue, 14 Jan 2025 02:17:01 GMT","x-kubernetes-pf-flowschema-uid":"93068417-329d-4e0f-9768-8a2b6794f954","x-kubernetes-pf-prioritylevel-uid":"f7dc9ee7-016c-48fa-afc3-77112540d77f"}
at CoreV1ApiResponseProcessor.patchNamespacedPodWithHttpInfo (/Users/I584817/Downloads/js-examples/node_modules/@kubernetes/client-node/dist/gen/apis/CoreV1Api.js:15722:15)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async file:///Users/XXX/Downloads/js-examples/merge-patch-example.js:46:5 {
code: 400,
body: '{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"error decoding patch: json: cannot unmarshal object into Go value of type []handlers.jsonPatchOp","reason":"BadRequest","code":400}\n',
headers: {
'audit-id': 'f2f1b40e-9d4a-49cf-af2b-989bed7de17e',
'cache-control': 'no-cache, private',
connection: 'close',
'content-length': '211',
'content-type': 'application/json',
date: 'Tue, 14 Jan 2025 02:17:01 GMT',
'x-kubernetes-pf-flowschema-uid': '93068417-329d-4e0f-9768-8a2b6794f954',
'x-kubernetes-pf-prioritylevel-uid': 'f7dc9ee7-016c-48fa-afc3-77112540d77f'
}
}
Please find my code in the example code below.
I tried to debug, and it seems that the pre function in the PromiseMiddlewareWrapper does not be executed.
I saw a Patch related issue [release-1.x] Patch namespace secret trigger an error due to unsupported media type, but it does not solve this issue.
Client Version
1.0.0
Server Version
1.31.0
To Reproduce
Save the below example code into file merge-patch-example.js, then execute the following commands.
npm i @kubernetes/client-node
node merge-patch-example.js
Expected behavior The server should not raise any error.
Example Code
import * as k8s from '@kubernetes/client-node';
import { PromiseMiddlewareWrapper } from '@kubernetes/client-node/dist/gen/middleware.js';
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
const namespace = 'default';
try {
const res = await k8sApi.listNamespacedPod({ namespace });
const body = {
metadata: {
labels: {
foo: 'bar2'
}
}
};
const headerPatchMiddleware = new PromiseMiddlewareWrapper({
pre: async (requestContext) => {
requestContext.setHeaderParam('Content-type', 'application/merge-patch+json');
return requestContext;
},
post: async (responseContext) => responseContext,
});
let currentContext = kc.getCurrentContext();
let currentCluster = kc.getCluster(currentContext);
if (currentCluster === undefined || currentCluster === null) {
throw new Error('Cluster is undefined');
}
let server = currentCluster.server;
if (server === undefined) {
throw new Error('Server is undefined');
}
const baseServerConfig = new k8s.ServerConfiguration(server, {});
const configuration = k8s.createConfiguration({
middleware: [headerPatchMiddleware],
baseServer: baseServerConfig,
authMethods: {
default: kc,
},
});
await k8sApi
.patchNamespacedPod(
{ name: res?.items?.[0].metadata?.name ?? '', namespace, body: body },
configuration,
)
console.log('Merged.');
} catch (err) {
console.error('Error: ');
console.error(err);
}
Environment (please complete the following information):
- OS: MacOS
- Node.js version 22.13.0
- Cloud runtime: Local Minikube
I confirmed this with patchNamespacedStatefulSet. pre() and post() are not called at all.
I found this as well today, with the code snippet very similar to the one of original author.
The API response is 400 Bad Request,
"error decoding patch: json: cannot unmarshal object into Go value of type []handlers.jsonPatchOp
Which hints that the servrer is expecting the array and not getting one.
I am using the middleware copypasted from the example
const headerPatchMiddleware = new PromiseMiddlewareWrapper({
pre: async (requestContext) => {
// requestContext.setHeaderParam("content-type", PatchStrategy.MergePatch);
requestContext.setHeaderParam("content-type", "application/merge-patch+json");
return requestContext;
},
post: async (responseContext) => responseContext,
});
Edit: it seems like middleware is not called at all when running the example code, neither pre nor post.
It looks like patchNamespacedPodWithHttpInfo() in dist/gen/types/ObservableAPI.js is not using the provided configuration object at all. It receives the custom configuration as its _options argument, but doesn't use it when setting up the middleware. Instead, it uses its this.configuration object.
Updating that function to do _config = _options || this.configuration; and then use _config, similar to what is done in other places in the codebase seems to make the middleware run.
I'm not sure if that is the ideal fix or not, because I'm not super familiar with the code generator codebase.
A second issue I noticed is that requestContext.setHeaderParam('Content-type', 'application/merge-patch+json'); needs to be Content-Type (note the capital T) in order to properly override the previous Content-Type header. I'm not sure if this is intentional or not. It kinda seems like a bug to me though.
After I made those two fixes locally, the code in the original post worked for me.
I can confirm the middleware just is not executing. Followed example from https://github.com/kubernetes-client/javascript/blob/main/examples/patch-example.js
It seems the primary use case for middleware is manually setting headers is to define the patch strategy. Could this just be added as an option on the patch methods like it is for KubernetesObjectApi.patch?
https://github.com/kubernetes-client/javascript/blob/247e4edd7afc70b3f685549bc4d08eafbdcdf0bf/src/object.ts#L230-L239
@brendandburns @mstruebing @davidgamero by any chance, do you know if my approach in https://github.com/kubernetes-client/javascript/issues/2160#issuecomment-2620169494 sounds correct? If so, I can send a patch to the code generator repo.
Your breakdown looks correct.
PR on the generator to attempt to fix this currently:
https://github.com/OpenAPITools/openapi-generator/pull/20430
The current discussion direction is going towards merging the middleware arrays from the base configuration and the _options.middleware
Let me know if any cases are missing from that approach
Thanks for the quick reply. I guess we will wait for that to land.
Hi guys, is there any workaround for this issue?
@waterscar To fix this we'll need to regen once https://github.com/OpenAPITools/openapi-generator/pull/20430 merges
https://github.com/OpenAPITools/openapi-generator/pull/20430 has been merged
#2275 is in progress
What are the next steps with this?
We'd need a release with these changes to get them accessible
@brendandburns @cjihrig are we okay with an rc to get this out?
@brendandburns how do you feel about publishing a v1.0.1?
Sounds good to me, I'll get on that.
So 1.1.0 is on trunk, but not yet deployed/pushed to npm.
v1.1.0 is released on npm now https://www.npmjs.com/package/@kubernetes/client-node/v/1.1.0
the setHeaderOptions method should significantly improve the ergonomics for this use case
@davidgamero can you please confirm that the setHeaderOptions returns the correct type to be passed to a patch method? When running your example I get:
$ npx tsx patch/patch-example.ts
Error: TypeError: callback(...).toPromise is not a function
at <anonymous> (/tmp/javascript/src/gen/rxjsStub.ts:22:40)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async <anonymous> (/tmp/javascript/examples/typescript/patch/patch-example.ts:25:5)
index.ts:31:9 - error TS2345: Argument of type 'ConfigurationOptions<PromiseMiddleware>' is not assignable to parameter of type 'ConfigurationOptions | undefined'.
Type 'ConfigurationOptions<PromiseMiddleware>' is not assignable to type 'ConfigurationOptions'.
Type 'ConfigurationOptions<PromiseMiddleware>' is not assignable to type 'Partial<Configuration<Middleware>>'.
Types of property 'middleware' are incompatible.
Type 'PromiseMiddleware[] | undefined' is not assignable to type 'Middleware[] | undefined'.
Type 'PromiseMiddleware[]' is not assignable to type 'Middleware[]'.
Type 'PromiseMiddleware' is not assignable to type 'Middleware'.
The types returned by 'pre(...)' are incompatible between these types.
Type 'Promise<RequestContext>' is missing the following properties from type 'Observable<RequestContext>': promise, toPromise, pipe
31 setHeaderOptions('Content-Type', PatchStrategy.JsonPatch),
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Found 1 error in index.ts:31
I can confirm that I have the same issue as karimodm.