Skip to content

Commit 5e49878

Browse files
feat(scheduler): marshal task properties as empty JSON not null
Task properties typing is problematic. Within SM server codebase, they are json.RawMessage. When returned to sctool or apps using SM client, they are interface{} which is carelessly cast to map[string]any. The problem is that nil task properties can't be cast to map[string]any. This results in unexpected errors and panics on sctool or apps using SM client side. Within SM codebase, we also make those such assumptions and sometimes ad-hoc replace nil properties with json.RawMessage(""). This commit doesn't fix anything on its own, but it makes it less likely that sctool or app using SM client breaks in those silly places by marshaling nil task properties as empty JSON object.
1 parent f5302a5 commit 5e49878

1 file changed

Lines changed: 13 additions & 1 deletion

File tree

pkg/service/scheduler/model.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ type Task struct {
259259
Deleted bool `json:"deleted,omitempty"`
260260
Sched Schedule `json:"schedule"`
261261
Properties json.RawMessage `json:"properties,omitempty"`
262-
Tags []string
262+
Tags []string `json:"tags,omitempty"`
263263

264264
Status Status `json:"status"`
265265
SuccessCount int `json:"success_count"`
@@ -268,6 +268,18 @@ type Task struct {
268268
LastError *time.Time `json:"last_error"`
269269
}
270270

271+
// MarshalJSON is a wrapper around default JSON marshaller ensuring
272+
// that Task.Properties are marshaled as an empty JSON object instead
273+
// of null. This makes it easier and safer on SM client side.
274+
func (t Task) MarshalJSON() ([]byte, error) {
275+
type Alias Task // To avoid infinite recursion
276+
taskWithFilledProps := Alias(t)
277+
if len(taskWithFilledProps.Properties) == 0 || string(taskWithFilledProps.Properties) == "null" {
278+
taskWithFilledProps.Properties = json.RawMessage("{}")
279+
}
280+
return json.Marshal(taskWithFilledProps)
281+
}
282+
271283
func (t *Task) String() string {
272284
return fmt.Sprintf("%s/%s", t.Type, t.ID)
273285
}

0 commit comments

Comments
 (0)