Blame view
payload.go
8.07 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" |
17a4d0447 mutex lock for pa... |
10 |
"sync" |
2ea67927f added support for... |
11 |
"time" |
1b7dfab73 Payload changed t... |
12 13 |
"git.to-net.rs/marko.tikvic/gologger" |
64041a2ea first commit |
14 |
) |
2ea67927f added support for... |
15 |
var ( |
3fffcb954 removed old http API |
16 17 |
mu = &sync.Mutex{} metadata = make(map[string]Payload) |
67337ffa8 payload editing |
18 |
updateQue = make(map[string][]byte) |
2ea67927f added support for... |
19 |
|
79071a5d4 Using database/sq... |
20 |
metadataDB *sql.DB |
2ea67927f added support for... |
21 22 23 |
activeProject string inited bool |
f84e7607d added dictionary;... |
24 |
driver string |
1b7dfab73 Payload changed t... |
25 |
logger *gologger.Logger |
2ea67927f added support for... |
26 |
) |
8dbe745c3 merged tables uti... |
27 |
|
64041a2ea first commit |
28 29 30 |
type LangMap map[string]map[string]string type Field struct { |
d2ddf82ef started on new rbac |
31 32 33 34 |
Parameter string `json:"param"` Type string `json:"type"` Visible bool `json:"visible"` Editable bool `json:"editable"` |
64041a2ea first commit |
35 |
} |
8dbe745c3 merged tables uti... |
36 37 38 39 40 41 42 |
type CorrelationField struct { Result string `json:"result"` Elements []string `json:"elements"` Type string `json:"type"` } type Translation struct { |
ecec68b18 updated todo list |
43 |
Language string `json:"language"` |
8dbe745c3 merged tables uti... |
44 |
FieldsLabels map[string]string `json:"fieldsLabels"` |
64041a2ea first commit |
45 |
} |
368c7f87b pagination work |
46 |
// output |
31a4e1302 started work on p... |
47 48 49 50 51 52 |
type PaginationLinks struct { Base string `json:"base"` Next string `json:"next"` Prev string `json:"prev"` Self string `json:"self"` } |
368c7f87b pagination work |
53 |
// input |
31a4e1302 started work on p... |
54 |
type PaginationParameters struct { |
368c7f87b pagination work |
55 |
URL string `json:"-"` |
31a4e1302 started work on p... |
56 57 58 59 60 |
Offset int64 `json:"offset"` Limit int64 `json:"limit"` SortBy string `json:"sortBy"` Order string `json:"order"` } |
368c7f87b pagination work |
61 62 63 64 65 66 67 68 69 |
// TODO(marko) func GetPaginationParameters(req *http.Request) (p PaginationParameters) { return p } // TODO(marko) func (p *PaginationParameters) paginationLinks() (links PaginationLinks) { return links } |
4a51e54d7 simplified |
70 |
type Payload struct { |
d2ddf82ef started on new rbac |
71 72 73 74 |
Method string `json:"method"` Params map[string]string `json:"params"` Lang []Translation `json:"lang"` Fields []Field `json:"fields"` |
4a51e54d7 simplified |
75 76 |
Correlations []CorrelationField `json:"correlationFields"` IdField string `json:"idField"` |
e1fbb41f9 added comments |
77 |
|
31a4e1302 started work on p... |
78 |
// Pagination |
368c7f87b pagination work |
79 80 81 |
Count int64 `json:"count"` Total int64 `json:"total"` Links PaginationLinks `json:"_links"` |
31a4e1302 started work on p... |
82 83 |
// Data holds JSON payload. It can't be used for itteration. |
d2ddf82ef started on new rbac |
84 |
Data interface{} `json:"data"` |
4a51e54d7 simplified |
85 |
} |
ad8e9dd2a added middleware ... |
86 87 88 |
func (p *Payload) SetData(data interface{}) { p.Data = data } |
368c7f87b pagination work |
89 |
func (p *Payload) SetPaginationInfo(count, total int64, params PaginationParameters) { |
31a4e1302 started work on p... |
90 91 |
p.Count = count p.Total = total |
368c7f87b pagination work |
92 |
p.Links = params.paginationLinks() |
31a4e1302 started work on p... |
93 |
} |
368c7f87b pagination work |
94 95 96 97 98 |
// 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... |
99 100 101 102 103 104 105 |
} // 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;... |
106 107 |
// InitPayloadsMetadata loads all payloads' information into 'metadata' variable. func InitPayloadsMetadata(drv string, db *sql.DB, project string) error { |
1b7dfab73 Payload changed t... |
108 |
var err error |
f84e7607d added dictionary;... |
109 |
if drv != "ora" && drv != "mysql" { |
1b7dfab73 Payload changed t... |
110 111 |
err = errors.New("driver not supported") return err |
f84e7607d added dictionary;... |
112 |
} |
1b7dfab73 Payload changed t... |
113 |
|
f84e7607d added dictionary;... |
114 |
driver = drv |
2ea67927f added support for... |
115 116 |
metadataDB = db activeProject = project |
62a69beda Init/Reload Table... |
117 |
|
1b7dfab73 Payload changed t... |
118 119 120 121 122 |
logger, err = gologger.New("metadata", gologger.MaxLogSize100KB) if err != nil { fmt.Printf("webutility: %s ", err.Error()) } |
2ea67927f added support for... |
123 124 |
mu.Lock() defer mu.Unlock() |
1b7dfab73 Payload changed t... |
125 |
err = initMetadata(project) |
d66628295 cleaned up |
126 127 128 |
if err != nil { return err } |
2ea67927f added support for... |
129 130 131 132 |
inited = true return nil } |
61efd58cd Put hotload enabl... |
133 134 135 136 137 |
func EnableHotloading(interval int) { if interval > 0 { go hotload(interval) } } |
67337ffa8 payload editing |
138 139 140 141 142 143 144 145 146 147 148 149 |
func GetMetadataForAllEntities() map[string]Payload { return metadata } func GetMetadataForEntity(t string) (Payload, bool) { p, ok := metadata[t] return p, ok } func QueEntityModelUpdate(entityType string, v interface{}) { updateQue[entityType], _ = json.Marshal(v) } |
63b2ae620 renamed files |
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
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 { return 0, 0, 0, errors.New("webutility: metadata not initialized but update was tried.") } total = len(updateQue) toUpdate := make([]string, 0) toAdd := make([]string, 0) for k, _ := range updateQue { 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... |
178 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
179 180 181 182 183 |
return } } else if driver == "mysql" { uStmt, err = metadataDB.Prepare("update entities set entity_model = ? where entity_type = ?") if err != nil { |
685dd6223 added error loggi... |
184 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
185 186 187 188 |
return } } for _, k := range toUpdate { |
63b2ae620 renamed files |
189 190 |
_, err = uStmt.Exec(string(updateQue[k]), k) if err != nil { |
685dd6223 added error loggi... |
191 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
192 193 194 195 196 197 198 199 200 201 |
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... |
202 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
203 204 205 206 207 |
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... |
208 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
209 210 211 212 213 214 |
return } } for _, k := range toAdd { _, err = iStmt.Exec(activeProject, string(blankPayload), k, string(updateQue[k])) if err != nil { |
685dd6223 added error loggi... |
215 |
logger.Trace(err.Error()) |
63b2ae620 renamed files |
216 217 218 219 220 221 222 223 |
return } metadata[k] = Payload{} add++ } return total, upd, add, nil } |
79071a5d4 Using database/sq... |
224 225 226 227 228 229 230 231 232 233 |
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... |
234 235 236 237 238 239 240 241 242 243 244 |
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 |
245 246 247 |
logger.Log("webutility: couldn't init: '%s' metadata: %s: %s ", name, err.Error(), load) |
79071a5d4 Using database/sq... |
248 |
} else { |
79071a5d4 Using database/sq... |
249 250 |
metadata[name] = p } |
79071a5d4 Using database/sq... |
251 |
} |
79071a5d4 Using database/sq... |
252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
return nil } 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;... |
266 267 |
logger.Log("webutility: hotload failed: %v ", err) |
79071a5d4 Using database/sq... |
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 |
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;... |
286 287 |
logger.Log("webutility: hotload rset error: %v ", rows.Err()) |
79071a5d4 Using database/sq... |
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
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;... |
326 327 328 |
logger.Log("webutility: couldn't refresh: '%s' metadata: %s %s ", e, err.Error(), load) |
79071a5d4 Using database/sq... |
329 330 331 332 333 334 335 |
} else { metadata[e] = p } } rows.Close() } } |
f84e7607d added dictionary;... |
336 |
/* |
67337ffa8 payload editing |
337 338 |
func ModifyMetadataForEntity(entityType string, p *Payload) error { md, err := json.Marshal(*p) |
2ea67927f added support for... |
339 340 341 |
if err != nil { return err } |
67337ffa8 payload editing |
342 |
|
d66628295 cleaned up |
343 344 |
mu.Lock() defer mu.Unlock() |
2ea67927f added support for... |
345 346 347 348 349 350 351 352 353 |
_, 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 |
354 355 356 |
} return nil } |
67337ffa8 payload editing |
357 358 359 360 361 362 363 364 |
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 |
365 |
} |
79071a5d4 Using database/sq... |
366 |
*/ |