77 cloudevents "github.com/cloudevents/sdk-go/v2"
88 cloudeventstypes "github.com/cloudevents/sdk-go/v2/types"
99 "github.com/google/uuid"
10+
1011 workpayload "open-cluster-management.io/sdk-go/pkg/cloudevents/clients/work/payload"
1112 cegeneric "open-cluster-management.io/sdk-go/pkg/cloudevents/generic"
1213 cetypes "open-cluster-management.io/sdk-go/pkg/cloudevents/generic/types"
@@ -31,6 +32,14 @@ func (codec *Codec) EventDataType() cetypes.CloudEventsDataType {
3132}
3233
3334func (codec * Codec ) Encode (source string , eventType cetypes.CloudEventsType , res * api.Resource ) (* cloudevents.Event , error ) {
35+ // use resource id as the resource payload metadata name to ensure the payload metadata name is
36+ // unique on the agent side
37+ if err := resetPayloadMetadataNameWithResID (res ); err != nil {
38+ return nil , err
39+ }
40+
41+ // converts a resource payload to a CloudEvent
42+ // If the the resource payload has metadata the event will have the metadata extension
3443 evt , err := api .JSONMAPToCloudEvent (res .Payload )
3544 if err != nil {
3645 return nil , fmt .Errorf ("failed to convert resource payload to cloudevent: %v" , err )
@@ -107,3 +116,20 @@ func (codec *Codec) Decode(evt *cloudevents.Event) (*api.Resource, error) {
107116
108117 return resource , nil
109118}
119+
120+ func resetPayloadMetadataNameWithResID (res * api.Resource ) error {
121+ metadata , ok := res .Payload [cetypes .ExtensionWorkMeta ]
122+ if ! ok {
123+ // the resource payload does not have metadata, do nothing
124+ // the agent will using resource id as the payload metadata name
125+ return nil
126+ }
127+
128+ metaObj , ok := metadata .(map [string ]interface {})
129+ if ! ok {
130+ return fmt .Errorf ("unsupported object type %T" , metadata )
131+ }
132+ metaObj ["name" ] = res .ID
133+ res .Payload [cetypes .ExtensionWorkMeta ] = metaObj
134+ return nil
135+ }
0 commit comments