aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/api_entity.go
blob: 04b9dca0b3e574f5a5cfac0fddef54099cdec30e (plain)
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package admin

import (
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

// The editor exposes the same list/get/create/update/delete contract for
// several YAML families. entityCRUD captures everything that actually
// differed between the hand-written copies; the handlers below are shared by
// every family.
//
// Two wire styles predate this file and must be preserved (see failJSON's
// contract comment):
//
//   - status style (items, drops, mobs, objects, hazards): errors are HTTP
//     error statuses with a JSON body; a successful write echoes the entity
//     map (including _raw).
//   - body style (techs, modules): errors are a 200 JSON body read as
//     res.error; writes reply {"ok":true,"id":id}. These editors also upsert
//     (POST/PUT by id creates an absent file).
type entityCRUD struct {
	route         string // URL segment and data subdirectory, e.g. "items"
	noun          string // singular for error text and undo descriptions
	searchSubdirs bool   // look the entity up in nested directories too
	upsert        bool   // by-ID POST/PUT creates an absent file
	bodyErr       bool   // write errors as a 200 JSON body (failJSON)
	okResponse    bool   // reply {"ok":true,"id":id} and "Created/Updated"
	refresh       func(*AdminServer)
}

var (
	itemSpec = entityCRUD{route: "items", noun: "item", searchSubdirs: true,
		refresh: func(s *AdminServer) { s.invalidateEntityCaches("items") }}
	dropSpec = entityCRUD{route: "drops", noun: "drop",
		refresh: func(s *AdminServer) { s.invalidateEntityCaches("drops") }}
	mobSpec = entityCRUD{route: "mobs", noun: "mob", searchSubdirs: true,
		refresh: func(s *AdminServer) { s.invalidateEntityCaches("mobs") }}
	objectSpec = entityCRUD{route: "objects", noun: "object", searchSubdirs: true,
		refresh: func(s *AdminServer) { s.invalidateEntityCaches("objects") }}
	hazardSpec = entityCRUD{route: "hazards", noun: "hazard",
		refresh: func(s *AdminServer) { s.world.ClearHazardCache() }}
	techSpec   = entityCRUD{route: "techs", noun: "tech", searchSubdirs: true, upsert: true, bodyErr: true, okResponse: true}
	moduleSpec = entityCRUD{route: "modules", noun: "module", searchSubdirs: true, upsert: true, bodyErr: true, okResponse: true}
)

func (c entityCRUD) find(s *AdminServer, id string) ([]byte, string, error) {
	if c.searchSubdirs {
		return findYAMLFileInSubdirs(s.dataDir, c.route, id)
	}
	return readYAMLFile(s.dataDir, c.route, id)
}

// fail writes an entity error in the family's wire style. status is ignored
// by the body style, whose clients read the error out of a 200.
func (c entityCRUD) fail(w http.ResponseWriter, status int, msg string) {
	if c.bodyErr {
		failJSON(w, msg)
		return
	}
	writeJSONError(w, msg, status)
}

func (c entityCRUD) invalidate(s *AdminServer) {
	if c.refresh != nil {
		c.refresh(s)
	}
}

func (c entityCRUD) invalidID() string {
	if c.bodyErr {
		return "invalid id"
	}
	return "invalid " + c.noun + " id"
}

func (c entityCRUD) missingID() string {
	if c.bodyErr {
		return "missing id"
	}
	return "missing " + c.noun + " id"
}

func (c entityCRUD) notFound(id string) string {
	if c.bodyErr {
		return "not found: " + id
	}
	return c.noun + " not found"
}

func (c entityCRUD) jsonErr(err error) string {
	if c.bodyErr {
		return "invalid JSON: " + err.Error()
	}
	return "invalid json body"
}

func (c entityCRUD) parseErr(err error) string {
	if c.bodyErr {
		return "parse error: " + err.Error()
	}
	return "failed to parse " + c.noun + " yaml"
}

func (c entityCRUD) writeErr(err error) string {
	if c.bodyErr {
		return "write error: " + err.Error()
	}
	return "failed to write " + c.noun
}

func (c entityCRUD) readErr(err error) string {
	if c.bodyErr {
		return "read existing file: " + err.Error()
	}
	return "failed to read existing " + c.noun
}

func (c entityCRUD) removeErr(err error) string {
	if c.bodyErr {
		return "delete error: " + err.Error()
	}
	return "failed to delete " + c.noun
}

func (c entityCRUD) listErr(err error) string {
	if c.bodyErr {
		return err.Error()
	}
	return "failed to list " + c.route
}

// desc names an undo entry. The body style uses past-tense verbs ("Created
// tech x"); the status style uses imperative ones ("Create item x").
func (c entityCRUD) desc(verb, okVerb, id string) string {
	if c.okResponse {
		return okVerb + " " + c.noun + " " + id
	}
	return verb + " " + c.noun + " " + id
}

// handleEntityList serves GET (tree) and POST (create) for one family.
func (s *AdminServer) handleEntityList(c entityCRUD) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodGet:
			tree, err := listYAMLTree(s.dataDir, c.route)
			if err != nil {
				c.fail(w, http.StatusInternalServerError, c.listErr(err))
				return
			}
			if tree == nil {
				tree = &YAMLTree{Root: []string{}, Dirs: map[string][]string{}}
			}
			writeJSON(w, tree)
		case http.MethodPost:
			s.entityCreate(w, r, c)
		default:
			methodNotAllowed(w)
		}
	}
}

// handleEntityByID serves GET/PUT/POST(upsert)/DELETE for one family.
func (s *AdminServer) handleEntityByID(c entityCRUD) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		id := strings.TrimPrefix(r.URL.Path, "/api/"+c.route+"/")
		if id == "" {
			c.fail(w, http.StatusBadRequest, c.missingID())
			return
		}
		if !validEntityID(id) {
			c.fail(w, http.StatusBadRequest, c.invalidID())
			return
		}
		switch r.Method {
		case http.MethodGet:
			s.entityGet(w, id, c)
		case http.MethodPut:
			s.entityUpdate(w, r, id, c)
		case http.MethodPost:
			if !c.upsert {
				methodNotAllowed(w)
				return
			}
			s.entityUpdate(w, r, id, c)
		case http.MethodDelete:
			s.entityDelete(w, id, c)
		default:
			methodNotAllowed(w)
		}
	}
}

func (s *AdminServer) entityGet(w http.ResponseWriter, id string, c entityCRUD) {
	data, path, err := c.find(s, id)
	if err != nil {
		c.fail(w, http.StatusNotFound, c.notFound(id))
		return
	}
	m, err := yamlToMap(data)
	if err != nil {
		c.fail(w, http.StatusInternalServerError, c.parseErr(err))
		return
	}
	if c.okResponse {
		// The body style strips the id before writing, so echo it from the
		// filename; the status style already writes it into the file.
		m["id"] = id
	}
	m["_path"] = path
	m["_raw"] = string(data)
	writeJSON(w, m)
}

func (s *AdminServer) entityCreate(w http.ResponseWriter, r *http.Request, c entityCRUD) {
	var m map[string]any
	if err := readJSON(r, &m); err != nil {
		c.fail(w, http.StatusBadRequest, c.jsonErr(err))
		return
	}
	id, ok := m["id"].(string)
	if !ok || strings.TrimSpace(id) == "" {
		c.fail(w, http.StatusBadRequest, c.missingID())
		return
	}
	if !validEntityID(id) {
		c.fail(w, http.StatusBadRequest, c.invalidID())
		return
	}
	// Editor-only keys never belong in the file (the update path drops them
	// too); without this a GET->POST round trip poisons the YAML.
	delete(m, "_path")
	delete(m, "_raw")
	if _, _, err := c.find(s, id); err == nil {
		c.fail(w, http.StatusConflict, c.noun+" already exists")
		return
	}
	if c.okResponse {
		delete(m, "id")
	}
	path := filepath.Join(s.dataDir, c.route, id+".yaml")
	newContent, err := writeMapAsYAML(path, m)
	if err != nil {
		c.fail(w, http.StatusInternalServerError, c.writeErr(err))
		return
	}
	s.undoStack.Push(ChangeDesc{
		Description: c.desc("Create", "Created", id),
		FilePath:    path,
		NewContent:  newContent,
		IsCreate:    true,
	})
	c.invalidate(s)
	if c.okResponse {
		writeJSON(w, map[string]any{"ok": true, "id": id})
		return
	}
	writeJSON(w, m)
}

func (s *AdminServer) entityUpdate(w http.ResponseWriter, r *http.Request, id string, c entityCRUD) {
	var m map[string]any
	if err := readJSON(r, &m); err != nil {
		c.fail(w, http.StatusBadRequest, c.jsonErr(err))
		return
	}
	_, path, findErr := c.find(s, id)
	isCreate := findErr != nil
	if isCreate && !c.upsert {
		c.fail(w, http.StatusNotFound, c.notFound(id))
		return
	}
	if isCreate {
		path = filepath.Join(s.dataDir, c.route, id+".yaml")
	}
	var oldContent []byte
	if !isCreate {
		var err error
		oldContent, err = snapshotFile(path)
		if err != nil {
			c.fail(w, http.StatusInternalServerError, c.readErr(err))
			return
		}
	}
	// _path/_raw are editor-only metadata and never belong in the file; the
	// status style also stores the id, while the body style derives it from
	// the filename.
	delete(m, "_path")
	delete(m, "_raw")
	if c.okResponse {
		delete(m, "id")
	} else {
		m["id"] = id
	}
	newContent, err := writeMapAsYAML(path, m)
	if err != nil {
		c.fail(w, http.StatusInternalServerError, c.writeErr(err))
		return
	}
	s.undoStack.Push(ChangeDesc{
		Description: c.desc("Update", "Updated", id),
		FilePath:    path,
		OldContent:  oldContent,
		NewContent:  newContent,
		IsCreate:    isCreate,
	})
	c.invalidate(s)
	if c.okResponse {
		writeJSON(w, map[string]any{"ok": true, "id": id})
		return
	}
	m["_raw"] = string(newContent)
	writeJSON(w, m)
}

func (s *AdminServer) entityDelete(w http.ResponseWriter, id string, c entityCRUD) {
	_, path, err := c.find(s, id)
	if err != nil {
		c.fail(w, http.StatusNotFound, c.notFound(id))
		return
	}
	oldContent := backupFile(path)
	if err := os.Remove(path); err != nil {
		c.fail(w, http.StatusInternalServerError, c.removeErr(err))
		return
	}
	s.undoStack.Push(ChangeDesc{
		Description: c.desc("Delete", "Deleted", id),
		FilePath:    path,
		OldContent:  oldContent,
		IsDelete:    true,
	})
	c.invalidate(s)
	if c.okResponse {
		writeJSON(w, map[string]any{"ok": true, "id": id})
		return
	}
	writeJSON(w, map[string]any{"deleted": id})
}

// methodNotAllowed writes the shared 405 body. The admin JS throws on any
// non-200, so the JSON form is safe for both wire styles.
func methodNotAllowed(w http.ResponseWriter) {
	http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}