# Copyright (C) 2018-2019 Lars Wirzenius # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . import ick2 class TransactionalResource: def __init__(self, state, kind, rid): self.state = state self.kind = kind self.rid = rid if state.has_resource(kind, rid): self.resource = state.get_resource(kind, rid) else: self.resource = ick2.resource_from_dict({}) methods = [ 'as_dict', '__getitem__', '__setitem__', '__contains__', '__len__', ] for method in methods: setattr(self, method, getattr(self.resource, method)) def __enter__(self): return self.resource def __exit__(self, exc_type, value, traceback): if exc_type is None: self.state.write_resource(self.kind, self.rid, self.resource) class TransactionalState: def __init__(self, state): self.state = state def new(self, kind, rid): return TransactionalResource(self.state, kind, rid) def modify(self, kind, rid): if not self.state.has_resource(kind, rid): raise ick2.NotFound(kind=kind, rid=rid) return TransactionalResource(self.state, kind, rid) def get_resource_ids(self, kind): return self.state.get_resource_ids(kind) def has_resource(self, kind, rid): return self.state.has_resource(kind, rid) def get_resource(self, kind, rid): return self.state.get_resource(kind, rid) def get_resources(self, kind): return self.state.get_resources(kind) def remove_resource(self, kind, rid): self.state.remove_resource(kind, rid)