summaryrefslogtreecommitdiffstats
path: root/aconf/model/node.lua
blob: fe816e82f3a765d50e9725a3f75efa7594d48f07 (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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
--[[
Copyright (c) 2012-2014 Kaarle Ritvanen
See LICENSE file for license details
--]]

local M = {}

local raise = require('aconf.error').raise

local object = require('aconf.object')
local class = object.class
local isinstance = object.isinstance
local super = object.super

local pth = require('aconf.path')

local util = require('aconf.util')
local copy = util.copy
local setdefaults = util.setdefaults
local update = util.update


function M.null_addr(path, name) return '/null'..pth.join(path, name) end


M.BoundMember = class()

function M.BoundMember:init(parent, name, field)
   local pmt = getmetatable(parent)
   local mt = {}

   function mt.__index(t, k)
      local member = field[k]
      if type(member) ~= 'function' then return member end

      local addr = field.addr or pth.escape(name)
      if type(addr) == 'function' then addr = addr(pmt.path, name) end
      return function(self, ...)
		return member(
		   field,
		   {
		      txn=pmt.txn,
		      privileged=pmt.privileged,
		      parent=parent,
		      path=pth.join(pmt.path, name),
		      addr=pth.to_absolute(addr, pmt.addr)
		   },
		   ...
		)
	     end
   end

   setmetatable(self, mt)
end


M.TreeNode = class()

local function equal_tns(tn1, tn2)
   return getmetatable(tn1).path == getmetatable(tn2).path
end

function M.TreeNode:init(context, params)
   local mt = getmetatable(self)
   update(mt, context)

   mt.name = pth.name(mt.path)
   mt.__eq = equal_tns

   if not (mt.txn and mt.txn.user) then mt.privileged = true end
   mt.escalate = mt.privileged and self or mt.class(
      setdefaults({privileged=true}, context), params
   )

   function mt.get(k, options) return mt.load(k, options) end


   function mt._fetch(path, create)
      if #path == 0 then return self end

      local name = path[1]
      table.remove(path, 1)

      if name == pth.up then
	 if not mt.parent then
	    raise(mt.path, 'Root object does not have parent')
	 end
	 return getmetatable(mt.parent)._fetch(path, create)
      end

      if not mt.member(name) then
	 raise(mt.path, 'Member does not exist: '..name)
      end

      local options = {}
      if create then
	 options.create = true
	 if #path == 0 then options.dereference = false end
      end
      local next = mt.get(name, options)
      if next == nil and (not create or #path > 0) then
	 raise(mt.path, 'Subordinate does not exist: '..name)
      end
      if #path == 0 then return next end

      if type(next) ~= 'table' then
	 raise(pth.join(mt.path, name), 'Is a primitive value')
      end

      return getmetatable(next)._fetch(path, create)
   end

   local cache = {}

   function mt.fetch(path, create)
      local res = cache[path]
      if res then return res end

      if pth.is_absolute(path) and mt.path > '/' then
	 assert(not create)
	 res = mt.txn:fetch(path, mt.privileged)

      else res = mt._fetch(pth.split(path), create) end

      if isinstance(res, M.TreeNode) then cache[path] = res end
      return res
   end


   local permissions = {}

   function mt._has_permission(permission) end

   function mt.has_permission(permission)
      if mt.privileged then return true end

      local name = permission..mt.path
      local res = permissions[name]
      if res ~= nil then return res end

      res = mt._has_permission(permission)

      if res == nil then
	 if getmetatable(mt.escalate).fetch('/auth/permissions')[name] then
	    res = mt.txn.user:check_permission(name)
	 else
	    if ({create=true, delete=true})[permission] then
	       permission = 'modify'
	    end
	    res = getmetatable(mt.parent).has_permission(permission)
	 end
      end

      permissions[name] = res
      return res
   end

   function mt.check_permission(permission)
      if not mt.has_permission(permission) then
	 raise('forbidden', permission..mt.path)
      end
   end


   function mt.removable() end

   function mt.value_removable(v)
      if isinstance(v, M.TreeNode) then return getmetatable(v).removable() end
   end

   local function key_removable(k)
      if not mt.removing_permitted() then return false end

      local res = mt.value_removable(mt.load(k, {dereference=false}))
      if res == nil then return params.editable end
      return res
   end

   function mt.check_removable(k)
      if not key_removable(k) then
	 raise(pth.join(mt.path, k), 'Cannot be deleted')
      end
   end

   function mt.meta()
      if not mt._meta then
	 mt._meta = {type=params.dtype}
	 if mt.txn then
	    if mt.parent then
	       mt._meta['ui-name'] =
		  getmetatable(mt.parent).mmeta(mt.name)['ui-name']
	    end
	    mt.init_meta(mt._meta)
	 end
      end

      local res = copy(mt._meta)
      res.removable = {}
      for _, key in ipairs(mt.members()) do
	 if key_removable(key) then table.insert(res.removable, key) end
      end
      return res
   end

   if not mt.txn then return end

   function mt.save(k, v) rawset(self, k, v) end
   function mt.__index(t, k) return mt.get(k, {private=true}) end
   function mt.__newindex(t, k, v) mt.save(k, v) end

   mt.txn.validable[mt.path] = mt.addr
end

function M.TreeNode:search_refs(path)
   if type(path) == 'string' then path = pth.split(path) end

   if #path == 0 then return {} end

   local mt = getmetatable(getmetatable(self).escalate)

   local name = path[1]
   table.remove(path, 1)

   local function collect(name)
      local next = mt.load(name, {dereference=false})
      if not next then return {} end
      
      local member = mt.member(name)
      if member.deleted then return {member} end
      
      return isinstance(next, M.TreeNode) and M.TreeNode.search_refs(
	 next, path
      ) or {}
   end

   if name == pth.wildcard then
      local res = {}
      for _, member in ipairs(mt.members()) do
	 util.extend(res, collect(member))
      end
      return res
   end

   return collect(name)
end


M.Collection = class(M.TreeNode)

function M.Collection:init(context, params)
   super(self, M.Collection):init(
      context, setdefaults(params, {dtype='collection'})
   )

   self.init = nil
   self.search_refs = nil

   local mt = getmetatable(self)
   local field = M.BoundMember(self, pth.wildcard, params.field)

   function mt.topology() return field:topology() end

   function mt.member(name)
      return M.BoundMember(self, name, params.field)
   end

   function mt.load(k, options) return mt.member(k):load(options) end

   function mt.removing_permitted() return mt.has_permission('delete') end

   if not mt.txn then return end

   function mt.init_meta(meta)
      update(
	 meta,
	 {
	    editable=params.editable and mt.has_permission('create'),
	    members=field:meta(),
	    required=params.required,
	    ['ui-member']=params.ui_member or meta['ui-name']:gsub('s$', ''),
	    widget=params.layout
	 }
      )
   end

   function mt.mmeta(name)
      local meta = mt.meta()
      local res = copy(meta.members)
      if name ~= pth.wildcard then
	 res['ui-name'] = meta['ui-member']..' '..name
      end
      return res
   end

   function mt.members() return mt.txn:get(mt.addr) or {} end

   function mt.__len() return #mt.members() end

   function mt.validate()
      if #mt.members() > 0 then return end
      if params.required then raise(mt.path, 'Collection cannot be empty') end
      if params.destroy then
	 mt.txn:set(mt.addr)
	 validate(mt.parent)
      end
   end

   function mt.save(k, v)
      local delete = v == nil
      local old = mt.load(k, {dereference=false})

      if old == nil then
	 if delete then return end
	 if not params.editable then
	    raise(mt.path, 'Collection is not editable')
	 end
	 mt.check_permission('create')

      elseif delete then mt.check_removable(k)

      elseif type(old) == 'table' then
	 mt.check_removable(k)
	 mt.check_permission('create')

      else mt.check_permission('modify') end


      if params.key then
	 local kf = M.BoundMember(self, k, params.key)
	 if kf:normalize(k) ~= k then
	    raise(mt.path, 'Invalid member name: '..k)
	 end
	 kf:validate(k)
      end

      mt.member(k):save(v)
   end
end


M.List = class(M.Collection)

function M.List:init(context, params)
   super(self, M.List):init(context, setdefaults(params, {dtype='list'}))

   local mt = getmetatable(self)
   local tmt = getmetatable(mt.escalate)

   mt._save = mt.save

   function mt.save(k, v)
      assert(type(k) == 'number')
      if v == nil then
	 mt.check_removable(k)
	 local len = #mt.members()
	 while k < len do
	    tmt._save(k, tmt.load(k + 1, {dereference=false}))
	    k = k + 1
	 end
	 tmt._save(len)
      else mt._save(k, v) end
   end

   function mt.insert(v, i)
      assert(v ~= nil)
      mt.check_permission('create')
      local len = #mt.members()
      if not i then i = len + 1 end
      for j = len,i,-1 do
	 tmt._save(j + 1, tmt.load(j, {dereference=false}))
      end
      tmt._save(i, v)
   end
end


-- experimental
M.Mixed = class(M.Collection)

function M.Mixed:init(context, params)
   super(self, M.Mixed):init(context, params)

   -- TODO dynamic meta: list non-leaf children
   local mt = getmetatable(self)
   mt.meta = {type='mixed', ['ui-name']=mt.path}
   function mt.mmeta(name)
      return {type='mixed', ['ui-name']=pth.join(mt.path, name)}
   end
end


local function meta_func(attr)
   return function(node, ...)
	     local res = getmetatable(node)[attr]
	     if type(res) == 'function' then return res(...) end
	     return res
	  end
end

for _, mf in ipairs{
   'addr',
   'check_permission',
   'contains',
   'escalate',
   'fetch',
   'has_permission',
   'insert',
   'meta',
   'mmeta',
   'name',
   'parent',
   'path',
   'save',
   'topology'
} do M[mf] = meta_func(mf) end


function M.pairs(tbl, dereference)
   if not isinstance(tbl, M.TreeNode) then return pairs(tbl) end

   local mt = getmetatable(tbl)

   local res = {}
   for _, member in ipairs(mt.members()) do
      res[member] = mt.load(member, {dereference=dereference})
   end
   return pairs(res)
end

local function _ipairs(mt, i)
   i = i + 1
   local v = mt.load(i, {create=false})
   if v == nil then return end
   return i, v
end
function M.ipairs(tbl)
   if not isinstance(tbl, M.TreeNode) then return ipairs(tbl) end
   return _ipairs, getmetatable(tbl), 0
end


return M