-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
95 lines (81 loc) · 2.17 KB
/
api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package platform_adapter
import (
"encoding/json"
"errors"
"os"
"rb/workload"
"strings"
)
type PlatformAdapter interface {
StartWorker(options map[string]interface{}) error
KillWorker(options map[string]interface{}) error
DeployFuncs(funcs []workload.Function) error
InvokeFunc(funcName string, timeout int, options map[string]interface{}) error
LoadConfig(config interface{}) error
GetStats() map[string]interface{}
}
type BasePlatformAdapter struct {
Config map[string]interface{}
// after each run, there might be some stats collected by the platform
// this map help to store those stats and can be easily accessed by the caller
Stats map[string]interface{}
}
// if config is a string, it is treated as a path to a json file; if it is a map, it is treated as a json object
func (c *BasePlatformAdapter) LoadConfig(config interface{}) error {
switch v := config.(type) {
case string:
file, err := os.Open(v)
if err != nil {
return err
}
defer file.Close()
decoder := json.NewDecoder(file)
err = decoder.Decode(&c.Config)
if err != nil {
return err
}
case map[string]interface{}:
c.Config = v
default:
return errors.New("unsupported config type")
}
return nil
}
func (c *BasePlatformAdapter) GetStats() map[string]interface{} {
return c.Stats
}
type Record interface {
GetHeaders() []string
ToSlice() []string
}
func FlushToFile(records []Record, filePath string) error {
if len(records) == 0 {
return nil
}
// Check if the file exists
_, err := os.Stat(filePath)
fileExists := !os.IsNotExist(err)
// Open the file for appending, creating it if it does not exist
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer file.Close()
// Write headers if the file did not exist
if !fileExists {
headers := records[0].GetHeaders() // Assuming records slice is not empty
_, err := file.WriteString(strings.Join(headers, ",") + "\n")
if err != nil {
return err
}
}
// Write each record to the file
for _, record := range records {
data := record.ToSlice()
_, err := file.WriteString(strings.Join(data, ",") + "\n")
if err != nil {
return err
}
}
return nil
}