channel.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. # Copyright 2014 Google Inc. All Rights Reserved.
  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. """Channel notifications support.
  15. Classes and functions to support channel subscriptions and notifications
  16. on those channels.
  17. Notes:
  18. - This code is based on experimental APIs and is subject to change.
  19. - Notification does not do deduplication of notification ids, that's up to
  20. the receiver.
  21. - Storing the Channel between calls is up to the caller.
  22. Example setting up a channel:
  23. # Create a new channel that gets notifications via webhook.
  24. channel = new_webhook_channel("https://example.com/my_web_hook")
  25. # Store the channel, keyed by 'channel.id'. Store it before calling the
  26. # watch method because notifications may start arriving before the watch
  27. # method returns.
  28. ...
  29. resp = service.objects().watchAll(
  30. bucket="some_bucket_id", body=channel.body()).execute()
  31. channel.update(resp)
  32. # Store the channel, keyed by 'channel.id'. Store it after being updated
  33. # since the resource_id value will now be correct, and that's needed to
  34. # stop a subscription.
  35. ...
  36. An example Webhook implementation using webapp2. Note that webapp2 puts
  37. headers in a case insensitive dictionary, as headers aren't guaranteed to
  38. always be upper case.
  39. id = self.request.headers[X_GOOG_CHANNEL_ID]
  40. # Retrieve the channel by id.
  41. channel = ...
  42. # Parse notification from the headers, including validating the id.
  43. n = notification_from_headers(channel, self.request.headers)
  44. # Do app specific stuff with the notification here.
  45. if n.resource_state == 'sync':
  46. # Code to handle sync state.
  47. elif n.resource_state == 'exists':
  48. # Code to handle the exists state.
  49. elif n.resource_state == 'not_exists':
  50. # Code to handle the not exists state.
  51. Example of unsubscribing.
  52. service.channels().stop(channel.body()).execute()
  53. """
  54. from __future__ import absolute_import
  55. import datetime
  56. import uuid
  57. from googleapiclient import _helpers as util
  58. from googleapiclient import errors
  59. # The unix time epoch starts at midnight 1970.
  60. EPOCH = datetime.datetime.utcfromtimestamp(0)
  61. # Map the names of the parameters in the JSON channel description to
  62. # the parameter names we use in the Channel class.
  63. CHANNEL_PARAMS = {
  64. "address": "address",
  65. "id": "id",
  66. "expiration": "expiration",
  67. "params": "params",
  68. "resourceId": "resource_id",
  69. "resourceUri": "resource_uri",
  70. "type": "type",
  71. "token": "token",
  72. }
  73. X_GOOG_CHANNEL_ID = "X-GOOG-CHANNEL-ID"
  74. X_GOOG_MESSAGE_NUMBER = "X-GOOG-MESSAGE-NUMBER"
  75. X_GOOG_RESOURCE_STATE = "X-GOOG-RESOURCE-STATE"
  76. X_GOOG_RESOURCE_URI = "X-GOOG-RESOURCE-URI"
  77. X_GOOG_RESOURCE_ID = "X-GOOG-RESOURCE-ID"
  78. def _upper_header_keys(headers):
  79. new_headers = {}
  80. for k, v in headers.items():
  81. new_headers[k.upper()] = v
  82. return new_headers
  83. class Notification(object):
  84. """A Notification from a Channel.
  85. Notifications are not usually constructed directly, but are returned
  86. from functions like notification_from_headers().
  87. Attributes:
  88. message_number: int, The unique id number of this notification.
  89. state: str, The state of the resource being monitored.
  90. uri: str, The address of the resource being monitored.
  91. resource_id: str, The unique identifier of the version of the resource at
  92. this event.
  93. """
  94. @util.positional(5)
  95. def __init__(self, message_number, state, resource_uri, resource_id):
  96. """Notification constructor.
  97. Args:
  98. message_number: int, The unique id number of this notification.
  99. state: str, The state of the resource being monitored. Can be one
  100. of "exists", "not_exists", or "sync".
  101. resource_uri: str, The address of the resource being monitored.
  102. resource_id: str, The identifier of the watched resource.
  103. """
  104. self.message_number = message_number
  105. self.state = state
  106. self.resource_uri = resource_uri
  107. self.resource_id = resource_id
  108. class Channel(object):
  109. """A Channel for notifications.
  110. Usually not constructed directly, instead it is returned from helper
  111. functions like new_webhook_channel().
  112. Attributes:
  113. type: str, The type of delivery mechanism used by this channel. For
  114. example, 'web_hook'.
  115. id: str, A UUID for the channel.
  116. token: str, An arbitrary string associated with the channel that
  117. is delivered to the target address with each event delivered
  118. over this channel.
  119. address: str, The address of the receiving entity where events are
  120. delivered. Specific to the channel type.
  121. expiration: int, The time, in milliseconds from the epoch, when this
  122. channel will expire.
  123. params: dict, A dictionary of string to string, with additional parameters
  124. controlling delivery channel behavior.
  125. resource_id: str, An opaque id that identifies the resource that is
  126. being watched. Stable across different API versions.
  127. resource_uri: str, The canonicalized ID of the watched resource.
  128. """
  129. @util.positional(5)
  130. def __init__(
  131. self,
  132. type,
  133. id,
  134. token,
  135. address,
  136. expiration=None,
  137. params=None,
  138. resource_id="",
  139. resource_uri="",
  140. ):
  141. """Create a new Channel.
  142. In user code, this Channel constructor will not typically be called
  143. manually since there are functions for creating channels for each specific
  144. type with a more customized set of arguments to pass.
  145. Args:
  146. type: str, The type of delivery mechanism used by this channel. For
  147. example, 'web_hook'.
  148. id: str, A UUID for the channel.
  149. token: str, An arbitrary string associated with the channel that
  150. is delivered to the target address with each event delivered
  151. over this channel.
  152. address: str, The address of the receiving entity where events are
  153. delivered. Specific to the channel type.
  154. expiration: int, The time, in milliseconds from the epoch, when this
  155. channel will expire.
  156. params: dict, A dictionary of string to string, with additional parameters
  157. controlling delivery channel behavior.
  158. resource_id: str, An opaque id that identifies the resource that is
  159. being watched. Stable across different API versions.
  160. resource_uri: str, The canonicalized ID of the watched resource.
  161. """
  162. self.type = type
  163. self.id = id
  164. self.token = token
  165. self.address = address
  166. self.expiration = expiration
  167. self.params = params
  168. self.resource_id = resource_id
  169. self.resource_uri = resource_uri
  170. def body(self):
  171. """Build a body from the Channel.
  172. Constructs a dictionary that's appropriate for passing into watch()
  173. methods as the value of body argument.
  174. Returns:
  175. A dictionary representation of the channel.
  176. """
  177. result = {
  178. "id": self.id,
  179. "token": self.token,
  180. "type": self.type,
  181. "address": self.address,
  182. }
  183. if self.params:
  184. result["params"] = self.params
  185. if self.resource_id:
  186. result["resourceId"] = self.resource_id
  187. if self.resource_uri:
  188. result["resourceUri"] = self.resource_uri
  189. if self.expiration:
  190. result["expiration"] = self.expiration
  191. return result
  192. def update(self, resp):
  193. """Update a channel with information from the response of watch().
  194. When a request is sent to watch() a resource, the response returned
  195. from the watch() request is a dictionary with updated channel information,
  196. such as the resource_id, which is needed when stopping a subscription.
  197. Args:
  198. resp: dict, The response from a watch() method.
  199. """
  200. for json_name, param_name in CHANNEL_PARAMS.items():
  201. value = resp.get(json_name)
  202. if value is not None:
  203. setattr(self, param_name, value)
  204. def notification_from_headers(channel, headers):
  205. """Parse a notification from the webhook request headers, validate
  206. the notification, and return a Notification object.
  207. Args:
  208. channel: Channel, The channel that the notification is associated with.
  209. headers: dict, A dictionary like object that contains the request headers
  210. from the webhook HTTP request.
  211. Returns:
  212. A Notification object.
  213. Raises:
  214. errors.InvalidNotificationError if the notification is invalid.
  215. ValueError if the X-GOOG-MESSAGE-NUMBER can't be converted to an int.
  216. """
  217. headers = _upper_header_keys(headers)
  218. channel_id = headers[X_GOOG_CHANNEL_ID]
  219. if channel.id != channel_id:
  220. raise errors.InvalidNotificationError(
  221. "Channel id mismatch: %s != %s" % (channel.id, channel_id)
  222. )
  223. else:
  224. message_number = int(headers[X_GOOG_MESSAGE_NUMBER])
  225. state = headers[X_GOOG_RESOURCE_STATE]
  226. resource_uri = headers[X_GOOG_RESOURCE_URI]
  227. resource_id = headers[X_GOOG_RESOURCE_ID]
  228. return Notification(message_number, state, resource_uri, resource_id)
  229. @util.positional(2)
  230. def new_webhook_channel(url, token=None, expiration=None, params=None):
  231. """Create a new webhook Channel.
  232. Args:
  233. url: str, URL to post notifications to.
  234. token: str, An arbitrary string associated with the channel that
  235. is delivered to the target address with each notification delivered
  236. over this channel.
  237. expiration: datetime.datetime, A time in the future when the channel
  238. should expire. Can also be None if the subscription should use the
  239. default expiration. Note that different services may have different
  240. limits on how long a subscription lasts. Check the response from the
  241. watch() method to see the value the service has set for an expiration
  242. time.
  243. params: dict, Extra parameters to pass on channel creation. Currently
  244. not used for webhook channels.
  245. """
  246. expiration_ms = 0
  247. if expiration:
  248. delta = expiration - EPOCH
  249. expiration_ms = (
  250. delta.microseconds / 1000 + (delta.seconds + delta.days * 24 * 3600) * 1000
  251. )
  252. if expiration_ms < 0:
  253. expiration_ms = 0
  254. return Channel(
  255. "web_hook",
  256. str(uuid.uuid4()),
  257. token,
  258. url,
  259. expiration=expiration_ms,
  260. params=params,
  261. )