httpresourcetree.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # Copyright 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import Dict
  16. from twisted.web.resource import NoResource, Resource
  17. logger = logging.getLogger(__name__)
  18. def create_resource_tree(
  19. desired_tree: Dict[str, Resource], root_resource: Resource
  20. ) -> Resource:
  21. """Create the resource tree for this homeserver.
  22. This in unduly complicated because Twisted does not support putting
  23. child resources more than 1 level deep at a time.
  24. Args:
  25. desired_tree: Dict from desired paths to desired resources.
  26. root_resource: The root resource to add the tree to.
  27. Returns:
  28. The ``root_resource`` with a tree of child resources added to it.
  29. """
  30. # ideally we'd just use getChild and putChild but getChild doesn't work
  31. # unless you give it a Request object IN ADDITION to the name :/ So
  32. # instead, we'll store a copy of this mapping so we can actually add
  33. # extra resources to existing nodes. See self._resource_id for the key.
  34. resource_mappings: Dict[str, Resource] = {}
  35. for full_path_str, res in desired_tree.items():
  36. # twisted requires all resources to be bytes
  37. full_path = full_path_str.encode("utf-8")
  38. logger.info("Attaching %s to path %s", res, full_path)
  39. last_resource = root_resource
  40. for path_seg in full_path.split(b"/")[1:-1]:
  41. if path_seg not in last_resource.listNames():
  42. # resource doesn't exist, so make a "dummy resource"
  43. child_resource: Resource = NoResource()
  44. last_resource.putChild(path_seg, child_resource)
  45. res_id = _resource_id(last_resource, path_seg)
  46. resource_mappings[res_id] = child_resource
  47. last_resource = child_resource
  48. else:
  49. # we have an existing Resource, use that instead.
  50. res_id = _resource_id(last_resource, path_seg)
  51. last_resource = resource_mappings[res_id]
  52. # ===========================
  53. # now attach the actual desired resource
  54. last_path_seg = full_path.split(b"/")[-1]
  55. # if there is already a resource here, thieve its children and
  56. # replace it
  57. res_id = _resource_id(last_resource, last_path_seg)
  58. if res_id in resource_mappings:
  59. # there is a dummy resource at this path already, which needs
  60. # to be replaced with the desired resource.
  61. existing_dummy_resource = resource_mappings[res_id]
  62. for child_name in existing_dummy_resource.listNames():
  63. child_res_id = _resource_id(existing_dummy_resource, child_name)
  64. child_resource = resource_mappings[child_res_id]
  65. # steal the children
  66. res.putChild(child_name, child_resource)
  67. # finally, insert the desired resource in the right place
  68. last_resource.putChild(last_path_seg, res)
  69. res_id = _resource_id(last_resource, last_path_seg)
  70. resource_mappings[res_id] = res
  71. return root_resource
  72. def _resource_id(resource: Resource, path_seg: bytes) -> str:
  73. """Construct an arbitrary resource ID so you can retrieve the mapping
  74. later.
  75. If you want to represent resource A putChild resource B with path C,
  76. the mapping should looks like _resource_id(A,C) = B.
  77. Args:
  78. resource: The *parent* Resourceb
  79. path_seg: The name of the child Resource to be attached.
  80. Returns:
  81. A unique string which can be a key to the child Resource.
  82. """
  83. return "%s-%r" % (resource, path_seg)