Blame view
payload.go
10.2 KB
ea858b8a7 refactoring |
1 |
package webutility |
64041a2ea first commit |
2 3 |
import ( |
79071a5d4 Using database/sq... |
4 |
"database/sql" |
8dbe745c3 merged tables uti... |
5 |
"encoding/json" |
f84e7607d added dictionary;... |
6 |
"errors" |
66478e04f payload now retur... |
7 |
"fmt" |
8dbe745c3 merged tables uti... |
8 |
"io" |
d2ddf82ef started on new rbac |
9 |
"net/http" |
68e590a60 load metadata fro... |
10 11 |
"os" "strings" |
17a4d0447 mutex lock for pa... |
12 |
"sync" |
2ea67927f added support for... |
13 |
"time" |
1b7dfab73 Payload changed t... |
14 15 |
"git.to-net.rs/marko.tikvic/gologger" |
64041a2ea first commit |
16 |
) |
2ea67927f added support for... |
17 |
var ( |
3fffcb954 removed old http API |
18 19 |
mu = &sync.Mutex{} metadata = make(map[string]Payload) |
67337ffa8 payload editing |
20 |
updateQue = make(map[string][]byte) |
2ea67927f added support for... |
21 |
|
79071a5d4 Using database/sq... |
22 |
metadataDB *sql.DB |
2ea67927f added support for... |
23 24 25 |
activeProject string inited bool |
f84e7607d added dictionary;... |
26 |
driver string |
1b7dfab73 Payload changed t... |
27 |
logger *gologger.Logger |
2ea67927f added support for... |
28 |
) |
8dbe745c3 merged tables uti... |
29 |
|
707782344 lint; vet |
30 |
// LangMap ... |
64041a2ea first commit |
31 |
type LangMap map[string]map[string]string |
707782344 lint; vet |
32 |
// Field ... |
64041a2ea first commit |
33 |
type Field struct { |
d2ddf82ef started on new rbac |
34 35 36 37 |
Parameter string `json:"param"` Type string `json:"type"` Visible bool `json:"visible"` Editable bool `json:"editable"` |
64041a2ea first commit |
38 |
} |
707782344 lint; vet |
39 |
// CorrelationField ... |
8dbe745c3 merged tables uti... |
40 41 42 43 44 |
type CorrelationField struct { Result string `json:"result"` Elements []string `json:"elements"` Type string `json:"type"` } |
707782344 lint; vet |
45 |
// Translation ... |
8dbe745c3 merged tables uti... |
46 |
type Translation struct { |
ecec68b18 updated todo list |
47 |
Language string `json:"language"` |
8dbe745c3 merged tables uti... |
48 |
FieldsLabels map[string]string `json:"fieldsLabels"` |
64041a2ea first commit |
49 |
} |
707782344 lint; vet |
50 |
// PaginationLinks ... |
31a4e1302 started work on p... |
51 52 53 54 55 56 |
type PaginationLinks struct { Base string `json:"base"` Next string `json:"next"` Prev string `json:"prev"` Self string `json:"self"` } |
707782344 lint; vet |
57 |
// PaginationParameters ... |
31a4e1302 started work on p... |
58 |
type PaginationParameters struct { |
368c7f87b pagination work |
59 |
URL string `json:"-"` |
31a4e1302 started work on p... |
60 61 62 63 64 |
Offset int64 `json:"offset"` Limit int64 `json:"limit"` SortBy string `json:"sortBy"` Order string `json:"order"` } |
707782344 lint; vet |
65 |
// GetPaginationParameters ... |
368c7f87b pagination work |
66 67 68 69 70 71 72 73 74 |
// TODO(marko) func GetPaginationParameters(req *http.Request) (p PaginationParameters) { return p } // TODO(marko) func (p *PaginationParameters) paginationLinks() (links PaginationLinks) { return links } |
707782344 lint; vet |
75 |
// Payload ... |
4a51e54d7 simplified |
76 |
type Payload struct { |
d2ddf82ef started on new rbac |
77 78 79 80 |
Method string `json:"method"` Params map[string]string `json:"params"` Lang []Translation `json:"lang"` Fields []Field `json:"fields"` |
4a51e54d7 simplified |
81 |
Correlations []CorrelationField `json:"correlationFields"` |
707782344 lint; vet |
82 |
IDField string `json:"idField"` |
e1fbb41f9 added comments |
83 |
|
31a4e1302 started work on p... |
84 |
// Pagination |
368c7f87b pagination work |
85 86 87 |
Count int64 `json:"count"` Total int64 `json:"total"` Links PaginationLinks `json:"_links"` |
31a4e1302 started work on p... |
88 89 |
// Data holds JSON payload. It can't be used for itteration. |
d2ddf82ef started on new rbac |
90 |
Data interface{} `json:"data"` |
4a51e54d7 simplified |
91 |
} |
8a070abe2 improved |
92 93 94 95 96 97 98 |
func (p *Payload) addLang(code string, labels map[string]string) { t := Translation{ Language: code, FieldsLabels: labels, } p.Lang = append(p.Lang, t) } |
707782344 lint; vet |
99 |
// SetData ... |
ad8e9dd2a added middleware ... |
100 101 102 |
func (p *Payload) SetData(data interface{}) { p.Data = data } |
707782344 lint; vet |
103 |
// SetPaginationInfo ... |
368c7f87b pagination work |
104 |
func (p *Payload) SetPaginationInfo(count, total int64, params PaginationParameters) { |
31a4e1302 started work on p... |
105 106 |
p.Count = count p.Total = total |
368c7f87b pagination work |
107 |
p.Links = params.paginationLinks() |
31a4e1302 started work on p... |
108 |
} |
368c7f87b pagination work |
109 110 111 112 113 |
// NewPayload returs a payload sceleton for entity described with key. func NewPayload(r *http.Request, key string) Payload { p := metadata[key] p.Method = r.Method + " " + r.RequestURI return p |
79071a5d4 Using database/sq... |
114 115 116 117 118 119 120 |
} // DecodeJSON decodes JSON data from r to v. // Returns an error if it fails. func DecodeJSON(r io.Reader, v interface{}) error { return json.NewDecoder(r).Decode(v) } |
f84e7607d added dictionary;... |
121 122 |
// InitPayloadsMetadata loads all payloads' information into 'metadata' variable. func InitPayloadsMetadata(drv string, db *sql.DB, project string) error { |
1b7dfab73 Payload changed t... |
123 |
var err error |
f84e7607d added dictionary;... |
124 |
if drv != "ora" && drv != "mysql" { |
1b7dfab73 Payload changed t... |
125 126 |
err = errors.New("driver not supported") return err |
f84e7607d added dictionary;... |
127 |
} |
1b7dfab73 Payload changed t... |
128 |
|
f84e7607d added dictionary;... |
129 |
driver = drv |
2ea67927f added support for... |
130 131 |
metadataDB = db activeProject = project |
62a69beda Init/Reload Table... |
132 |
|
1b7dfab73 Payload changed t... |
133 134 135 136 137 |
logger, err = gologger.New("metadata", gologger.MaxLogSize100KB) if err != nil { fmt.Printf("webutility: %s ", err.Error()) } |
2ea67927f added support for... |
138 139 |
mu.Lock() defer mu.Unlock() |
1b7dfab73 Payload changed t... |
140 |
err = initMetadata(project) |
d66628295 cleaned up |
141 142 143 |
if err != nil { return err } |
2ea67927f added support for... |
144 145 146 147 |
inited = true return nil } |
707782344 lint; vet |
148 |
// EnableHotloading ... |
61efd58cd Put hotload enabl... |
149 150 151 152 153 |
func EnableHotloading(interval int) { if interval > 0 { go hotload(interval) } } |
707782344 lint; vet |
154 |
// GetMetadataForAllEntities ... |
67337ffa8 payload editing |
155 156 157 |
func GetMetadataForAllEntities() map[string]Payload { return metadata } |
707782344 lint; vet |
158 |
// GetMetadataForEntity ... |
67337ffa8 payload editing |
159 160 161 162 |
func GetMetadataForEntity(t string) (Payload, bool) { p, ok := metadata[t] return p, ok } |
707782344 lint; vet |
163 |
// QueEntityModelUpdate ... |
67337ffa8 payload editing |
164 165 166 |
func QueEntityModelUpdate(entityType string, v interface{}) { updateQue[entityType], _ = json.Marshal(v) } |
707782344 lint; vet |
167 |
// UpdateEntityModels ... |
63b2ae620 renamed files |
168 169 170 171 172 173 |
func UpdateEntityModels(command string) (total, upd, add int, err error) { if command != "force" && command != "missing" { return total, 0, 0, errors.New("webutility: unknown command: " + command) } if !inited { |
707782344 lint; vet |
174 |
return 0, 0, 0, errors.New("webutility: metadata not initialized but update was tried") |
63b2ae620 renamed files |
175 176 177 178 179 180 |
} total = len(updateQue) toUpdate := make([]string, 0) toAdd := make([]string, 0) |
707782344 lint; vet |
181 |
for k := range updateQue { |
63b2ae620 renamed files |
182 183 184 185 186 187 188 189 190 191 192 193 194 |
if _, exists := metadata[k]; exists { if command == "force" { toUpdate = append(toUpdate, k) } } else { toAdd = append(toAdd, k) } } var uStmt *sql.Stmt if driver == "ora" { uStmt, err = metadataDB.Prepare("update entities set entity_model = :1 where entity_type = :2") if err != nil { |
685dd6223 added error loggi... |
195 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
196 197 198 199 200 |
return } } else if driver == "mysql" { uStmt, err = metadataDB.Prepare("update entities set entity_model = ? where entity_type = ?") if err != nil { |
685dd6223 added error loggi... |
201 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
202 203 204 205 |
return } } for _, k := range toUpdate { |
63b2ae620 renamed files |
206 207 |
_, err = uStmt.Exec(string(updateQue[k]), k) if err != nil { |
685dd6223 added error loggi... |
208 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
209 210 211 212 213 214 215 216 217 218 |
return } upd++ } blankPayload, _ := json.Marshal(Payload{}) var iStmt *sql.Stmt if driver == "ora" { iStmt, err = metadataDB.Prepare("insert into entities(projekat, metadata, entity_type, entity_model) values(:1, :2, :3, :4)") if err != nil { |
685dd6223 added error loggi... |
219 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
220 221 222 223 224 |
return } } else if driver == "mysql" { iStmt, err = metadataDB.Prepare("insert into entities(projekat, metadata, entity_type, entity_model) values(?, ?, ?, ?)") if err != nil { |
685dd6223 added error loggi... |
225 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
226 227 228 229 230 231 |
return } } for _, k := range toAdd { _, err = iStmt.Exec(activeProject, string(blankPayload), k, string(updateQue[k])) if err != nil { |
685dd6223 added error loggi... |
232 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
233 234 235 236 237 238 239 240 |
return } metadata[k] = Payload{} add++ } return total, upd, add, nil } |
79071a5d4 Using database/sq... |
241 242 243 244 245 246 247 248 249 250 |
func initMetadata(project string) error { rows, err := metadataDB.Query(`select entity_type, metadata from entities where projekat = ` + fmt.Sprintf("'%s'", project)) if err != nil { return err } defer rows.Close() |
79071a5d4 Using database/sq... |
251 252 253 254 255 256 257 258 259 260 261 |
if len(metadata) > 0 { metadata = nil } metadata = make(map[string]Payload) for rows.Next() { var name, load string rows.Scan(&name, &load) p := Payload{} err := json.Unmarshal([]byte(load), &p) if err != nil { |
63b2ae620 renamed files |
262 263 264 |
logger.Log("webutility: couldn't init: '%s' metadata: %s: %s ", name, err.Error(), load) |
79071a5d4 Using database/sq... |
265 |
} else { |
79071a5d4 Using database/sq... |
266 267 |
metadata[name] = p } |
79071a5d4 Using database/sq... |
268 |
} |
79071a5d4 Using database/sq... |
269 270 271 |
return nil } |
707782344 lint; vet |
272 |
// LoadMetadataFromFile expects file in format: |
8a070abe2 improved |
273 274 275 276 277 278 279 280 281 |
// // [ payload A identifier ] // key1 : value1 // key2 : value2 // ... // [ payload B identifier ] // key1 : value1 // key2 : value2 // ... |
707782344 lint; vet |
282 283 |
// // TODO(marko): Currently supports only one hardcoded language... |
68e590a60 load metadata fro... |
284 |
func LoadMetadataFromFile(path string) error { |
3ad172fb6 refactored and ma... |
285 |
lines, err := ReadFileLines(path) |
68e590a60 load metadata fro... |
286 287 288 |
if err != nil { return err } |
68e590a60 load metadata fro... |
289 290 291 |
metadata = make(map[string]Payload) var name string |
3ad172fb6 refactored and ma... |
292 |
for i, l := range lines { |
8a070abe2 improved |
293 294 |
// skip empty lines if l = trimSpaces(l); len(l) == 0 { |
3ad172fb6 refactored and ma... |
295 296 |
continue } |
8a070abe2 improved |
297 |
if isWrappedWith(l, "[", "]") { |
68e590a60 load metadata fro... |
298 |
name = strings.Trim(l, "[]") |
8a070abe2 improved |
299 300 301 |
p := Payload{} p.addLang("sr", make(map[string]string)) metadata[name] = p |
68e590a60 load metadata fro... |
302 303 |
continue } |
3ad172fb6 refactored and ma... |
304 |
if name == "" { |
707782344 lint; vet |
305 |
return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [no header] [%s]", i+1, l) |
3ad172fb6 refactored and ma... |
306 |
} |
68e590a60 load metadata fro... |
307 |
parts := strings.Split(l, ":") |
8a070abe2 improved |
308 |
if len(parts) != 2 { |
707782344 lint; vet |
309 |
return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [invalid format] [%s]", i+1, l) |
3ad172fb6 refactored and ma... |
310 |
} |
8a070abe2 improved |
311 312 |
k := trimSpaces(parts[0]) v := trimSpaces(parts[1]) |
3ad172fb6 refactored and ma... |
313 314 |
if v != "-" { metadata[name].Lang[0].FieldsLabels[k] = v |
68e590a60 load metadata fro... |
315 316 317 318 319 |
} } return nil } |
8a070abe2 improved |
320 321 322 323 324 325 326 |
func isWrappedWith(src, begin, end string) bool { return strings.HasPrefix(src, begin) && strings.HasSuffix(src, end) } func trimSpaces(s string) string { return strings.TrimSpace(s) } |
707782344 lint; vet |
327 |
// ReadFileLines ... |
1257b237a todo |
328 |
// TODO(marko): Move to separate package |
3ad172fb6 refactored and ma... |
329 |
func ReadFileLines(path string) ([]string, error) { |
68e590a60 load metadata fro... |
330 331 332 333 334 335 336 |
f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() var s strings.Builder |
3ad172fb6 refactored and ma... |
337 |
|
44c82dbac simplified file r... |
338 339 |
if _, err = io.Copy(&s, f); err != nil { return nil, err |
68e590a60 load metadata fro... |
340 |
} |
3ad172fb6 refactored and ma... |
341 342 |
lines := strings.Split(s.String(), " ") |
68e590a60 load metadata fro... |
343 344 345 |
return lines, nil } |
79071a5d4 Using database/sq... |
346 347 348 349 350 351 352 353 354 355 |
func hotload(n int) { entityScan := make(map[string]int64) firstCheck := true for { time.Sleep(time.Duration(n) * time.Second) rows, err := metadataDB.Query(`select ora_rowscn, entity_type from entities where projekat = ` + fmt.Sprintf("'%s'", activeProject)) if err != nil { |
f84e7607d added dictionary;... |
356 357 |
logger.Log("webutility: hotload failed: %v ", err) |
79071a5d4 Using database/sq... |
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
time.Sleep(time.Duration(n) * time.Second) continue } var toRefresh []string for rows.Next() { var scanID int64 var entity string rows.Scan(&scanID, &entity) oldID, ok := entityScan[entity] if !ok || oldID != scanID { entityScan[entity] = scanID toRefresh = append(toRefresh, entity) } } rows.Close() if rows.Err() != nil { |
f84e7607d added dictionary;... |
376 377 |
logger.Log("webutility: hotload rset error: %v ", rows.Err()) |
79071a5d4 Using database/sq... |
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 |
time.Sleep(time.Duration(n) * time.Second) continue } if len(toRefresh) > 0 && !firstCheck { mu.Lock() refreshMetadata(toRefresh) mu.Unlock() } if firstCheck { firstCheck = false } } } func refreshMetadata(entities []string) { for _, e := range entities { fmt.Printf("refreshing %s ", e) rows, err := metadataDB.Query(`select metadata from entities where projekat = ` + fmt.Sprintf("'%s'", activeProject) + ` and entity_type = ` + fmt.Sprintf("'%s'", e)) if err != nil { logger.Log("webutility: refresh: prep: %v ", err) rows.Close() continue } for rows.Next() { var load string rows.Scan(&load) p := Payload{} err := json.Unmarshal([]byte(load), &p) if err != nil { |
f84e7607d added dictionary;... |
416 417 418 |
logger.Log("webutility: couldn't refresh: '%s' metadata: %s %s ", e, err.Error(), load) |
79071a5d4 Using database/sq... |
419 420 421 422 423 424 425 |
} else { metadata[e] = p } } rows.Close() } } |
f84e7607d added dictionary;... |
426 |
/* |
67337ffa8 payload editing |
427 428 |
func ModifyMetadataForEntity(entityType string, p *Payload) error { md, err := json.Marshal(*p) |
2ea67927f added support for... |
429 430 431 |
if err != nil { return err } |
67337ffa8 payload editing |
432 |
|
d66628295 cleaned up |
433 434 |
mu.Lock() defer mu.Unlock() |
2ea67927f added support for... |
435 436 437 438 439 440 441 442 443 |
_, err = metadataDB.PrepAndExe(`update entities set metadata = :1 where projekat = :2 and entity_type = :3`, string(md), activeProject, entityType) if err != nil { return err |
d66628295 cleaned up |
444 445 446 |
} return nil } |
67337ffa8 payload editing |
447 448 449 450 451 452 453 454 |
func DeleteEntityModel(entityType string) error { _, err := metadataDB.PrepAndExe("delete from entities where entity_type = :1", entityType) if err == nil { mu.Lock() delete(metadata, entityType) mu.Unlock() } return err |
d66628295 cleaned up |
455 |
} |
79071a5d4 Using database/sq... |
456 |
*/ |