nti.webhooks.interfaces

Interface definitions for nti.webhooks.

interface nti.webhooks.interfaces.ICreatedTime[source]

Something that (immutably) tracks its created time.

createdTime

The timestamp at which this object was created.

Typically set automatically by the object.

Implementation:zope.schema.Real
Read Only:False
Required:True
Default Value:0.0
Allowed Type:numbers.Real
interface nti.webhooks.interfaces.ILastModified[source]

Extends: nti.webhooks.interfaces.ICreatedTime

Something that tracks a modification timestamp.

lastModified

The timestamp at which this object or its contents was last modified.

Implementation:zope.schema.Real
Read Only:False
Required:True
Default Value:0.0
Allowed Type:numbers.Real
interface nti.webhooks.interfaces.ILimitedApplicabilityPreconditionFailureWebhookSubscription[source]

Extends: nti.webhooks.interfaces.IWebhookSubscription

A webhook subscription that supports a limit on the number of times checking applicability can be allowed to fail.

When this number is exceeded, an event implementing IWebhookSubscriptionApplicabilityPreconditionFailureLimitReached is notified.

applicable_precondition_failure_limit

An integer giving the number of times applicability checks can fail before the event is generated.

interface nti.webhooks.interfaces.ILimitedAttemptWebhookSubscription[source]

Extends: nti.webhooks.interfaces.IWebhookSubscription

A webhook subscription that should limit the number of delivery attempts it stores.

attempt_limit

An integer giving approximately the number of delivery attempts this object will store. This is also used to deactivate the subscription when this many attempts in a row have failed.

interface nti.webhooks.interfaces.IPossibleWebhookPayload[source]

Marker interface applied to objects that may have webhook subscriptions defined for them.

The default configuration in subscribers.zcml loads event dispatchers only for event targets that implement this interface.

interface nti.webhooks.interfaces.IWebhookDeliveryAttempt[source]

Extends: nti.webhooks.interfaces._ITimes, zope.location.interfaces.IContained

The duration of the request/reply cycle is roughly captured by the difference in the createdTime attributes of the request and response. More precisely, the network time is captured by the elapsed attribute of the response.

__parent__
Implementation:zope.schema.Field
Read Only:False
Required:True
Default Value:None
status

The status of the delivery attempt.

The current status of the delivery attempt.

Attempts begin in the ‘pending’ state, and then transition to either the ‘successful’, or ‘failed’ state.

Implementation:nti.webhooks.interfaces._StatusField
Read Only:False
Required:True
Default Value:‘pending’
message

Additional explanatory text.

Implementation:nti.schema.field.ValidText
Read Only:False
Required:False
Default Value:None
Allowed Type:str
internal_info
Implementation:nti.schema.field.Object
Read Only:False
Required:True
Default Value:None
Must Provide:nti.webhooks.interfaces.IWebhookDeliveryAttemptInternalInfo
request
Implementation:nti.schema.field.Object
Read Only:False
Required:True
Default Value:None
Must Provide:nti.webhooks.interfaces.IWebhookDeliveryAttemptRequest
response
Implementation:nti.schema.field.Object
Read Only:False
Required:True
Default Value:None
Must Provide:nti.webhooks.interfaces.IWebhookDeliveryAttemptResponse
succeeded()

Did the attempt succeed?

failed()

Did the attempt fail?

pending()

Is the attempt still pending?

resolved()

Has the attempt been resolved, one way or the other?

interface nti.webhooks.interfaces.IWebhookDeliveryAttemptFailedEvent[source]

Extends: nti.webhooks.interfaces.IWebhookDeliveryAttemptResolvedEvent

A delivery attempt failed.

The succeeded attribute will be false.

interface nti.webhooks.interfaces.IWebhookDeliveryAttemptInternalInfo[source]

Extends: nti.webhooks.interfaces._ITimes

Internal (debugging) information stored with a delivery attempt.

This data is never externalized and is only loosely specified.

It may change over time.

exception_history

A sequence (oldest to newest) of information about exceptions encountered processing the attempt.

originated

Information about where and how the request originated. This can be used to see if it might still be pending or if the instance has gone away.

interface nti.webhooks.interfaces.IWebhookDeliveryAttemptRequest[source]

Extends: nti.webhooks.interfaces._ITimes

The details about an HTTP request sent to a webhook.

url

The URL requested

This is denormalized from the containing delivery attempt and its containing subscription because the target URL may change over time.

Implementation:nti.schema.field.ValidURI
Read Only:False
Required:True
Default Value:None
Allowed Type:str
method

The HTTP method the request was sent with.

Implementation:nti.schema.field.ValidText
Read Only:False
Required:True
Default Value:‘POST’
Allowed Type:str
body

The external data sent to the destination.

Implementation:nti.schema.field.ValidText
Read Only:False
Required:True
Default Value:None
Allowed Type:str
headers

The headers sent with the request.

Order is not kept. Security sensitive headers, such as those relating to authentication, are removed.

Implementation:zope.schema.Dict
Read Only:False
Required:True
Default Value:None
Allowed Type:dict

Key Type

Implementation:nti.schema.field.ValidText
Read Only:False
Required:True
Default Value:None
Allowed Type:str

Value Type

Implementation:nti.schema.field.ValidText
Read Only:False
Required:True
Default Value:None
Allowed Type:str
interface nti.webhooks.interfaces.IWebhookDeliveryAttemptResolvedEvent[source]

Extends: zope.lifecycleevent.interfaces.IObjectModifiedEvent

A pending webhook delivery attempt has been completed.

This is an object modified event; the object is the attempt.

This is the root of a hierarchy; more specific events are in IWebhookDeliveryAttemptFailedEvent and IWebhookDeliveryAttemptSucceededEvent.

succeeded

Was the delivery attempt successful?

Implementation:zope.schema.Bool
Read Only:False
Required:True
Default Value:None
Allowed Type:bool
interface nti.webhooks.interfaces.IWebhookDeliveryAttemptResponse[source]

Extends: nti.webhooks.interfaces._ITimes

The details about the HTTP response.

  • HTTP redirect history is lost; only the final response is saved.
status_code

The HTTP status code

For example, 200.

Implementation:nti.schema.field.Int
Read Only:False
Required:True
Default Value:None
Allowed Type:int
reason

The HTTP reason.

For example, ‘OK’

Implementation:nti.schema.field.ValidText
Read Only:False
Required:True
Default Value:None
Allowed Type:str
headers

The headers received from the server.

Implementation:zope.schema.Dict
Read Only:False
Required:True
Default Value:None
Allowed Type:dict

Key Type

Implementation:nti.schema.field.ValidText
Read Only:False
Required:True
Default Value:None
Allowed Type:str

Value Type

Implementation:nti.schema.field.ValidText
Read Only:False
Required:True
Default Value:None
Allowed Type:str
content

The decoded contents of the response, if any.

If the response contained a body, but it wasn’t decodable as text, XXX: What?

TODO: Place some limits on this?

Implementation:nti.schema.field.ValidText
Read Only:False
Required:False
Default Value:None
Allowed Type:str
elapsed

The amount of time it took to send and receive.

This should be the closest measurement possible of the time taken between sending the first byte of the request, and receiving a usable response.

Implementation:zope.schema.Timedelta
Read Only:False
Required:True
Default Value:None
Allowed Type:datetime.timedelta
interface nti.webhooks.interfaces.IWebhookDeliveryAttemptSucceededEvent[source]

Extends: nti.webhooks.interfaces.IWebhookDeliveryAttemptResolvedEvent

A delivery attempt succeeded.

The succeeded attribute will be true.

interface nti.webhooks.interfaces.IWebhookDeliveryManager[source]

Handles the delivery of messages.

This is a global utility registered by the ZCML of this package.

It operates in fire-and-forget mode, in a completely opaque fashion. However, this is a two-step process to better work with persistent objects and transactions. In the first step, a IWebhookDeliveryManagerShipmentInfo is created with createShipmentInfo(), packaging up all the information needed to later begin the delivery using acceptForDelivery().

(And yes, the terminology is based on the United States Postal Service.)

createShipmentInfo(subscriptions_and_attempts)

Given an (distinct) iterable of (subscription, attempt) pairs, extract the information needed to later send that data as well as record its status in the subscription, independently of any currently running transaction or request.

Each attempt must be pending and must not be contained in any other shipment info.

For persistent subscriptions and attempts, all necessary information to complete acceptForDelivery() must be captured at this time. The connection that created the subscription and attempts must still be open, and the transaction still running.

Returns:A new IWebhookDeliveryManagerShipmentInfo object. If the iterable is empty, this may return None or a suitable object that causes acceptForDelivery() to behave appropriately.
acceptForDelivery(shipment_info)

Given a IWebhookDeliveryManagerShipmentInfo previously created by this object but not yet accepted for delivery, schedule the delivery and begin making it happen.

This is generally an asynchronous call and SHOULD NOT raise exceptions; the caller is likely unable to deal with them.

As delivery completes, the status of each attempt contained in the shipment info should be updated.

No return value.

interface nti.webhooks.interfaces.IWebhookDeliveryManagerShipmentInfo[source]

A largely-opaque interface representing values returned from, and passed to, a particular IWebhookDeliveryManager.

interface nti.webhooks.interfaces.IWebhookDestinationValidator[source]

Validates destinations.

This is the place where we make sure that the destination is valid, before attempting to deliver to it, according to policy. This may include such things as:

  • Check that the protocol is HTTPs.
  • Verify that the domain is reachable, or at least resolvable.
  • Ensure query parameters are innocuous

Targets are validated before attempting to send data to them.

This is registered as a single global utility. The utility is encouraged to cache valid/invalid results for a period of time, especially with domain resolvability.

validateTarget(target_url)

Check that the URL is valid. If it is, return silently.

If it is not, raise some sort of exception such as a socket.error for unresolvable domains.

interface nti.webhooks.interfaces.IWebhookDialect[source]

Provides control over what data is sent on the wire.

externalizeData(data, event)

Produce the byte-string that is the externalized version of data needed to send to webhooks using this dialect.

This is called while the transaction that triggered the event is still open and not yet committed.

The default method will externalize the data using an nti.externalization externalizer named “webhook-delivery”.

prepareRequest(http_session, subscription, attempt)

Produce the prepared request to send.

Parameters:
  • http_session (requests.Session) – The session being used to send requests. The implementation should generally create a requests.Request object, and then prepare it with requests.Session.prepare_request() to combine the two.
  • subscription (IWebhookSubscription) – The subscription that is being delivered.
  • attempt (IWebhookDeliveryAttempt) – The attempt being sent. It will already have its payload_data, which should be given as the data argument to the request.
Return type:

requests.PreparedRequest

Caution

It may not be possible to access attributes of persistent objects

interface nti.webhooks.interfaces.IWebhookPayload[source]

Adapter interface to convert an object that is a target of an event (possibly a IPossibleWebhookPayload) into the object that should actually be used as the payload.

interface nti.webhooks.interfaces.IWebhookPrincipal[source]

A minimal version of zope.security.interfaces.IPrincipal.

This is used by this package when we need to convert an arbitrary object into something that can match up with a owner_id, as used by IWebhookSubscription. It is useful if your own objects don’t adapt to or implement IPrincipal.

See also

nti.webhooks.subscribers.remove_subscriptions_for_principal

id

Id

The unique identification of the principal.

Implementation:nti.schema.field.ValidTextLine
Read Only:True
Required:True
Default Value:None
Allowed Type:str
interface nti.webhooks.interfaces.IWebhookResourceDiscriminator[source]

An adapter that can figure out a better for for a resource than simply what it provides.

__call__()

Return the value to use for for.

interface nti.webhooks.interfaces.IWebhookSubscription[source]

Extends: nti.webhooks.interfaces._ITimes, zope.container.interfaces.IContainerNamesContainer

An individual subscription.

__parent__
Implementation:zope.schema.Field
Read Only:False
Required:True
Default Value:None
for_

The type of object to attempt delivery for.

When object events of type when are fired for instances providing this interface, webhook delivery to target might be attempted.

The default is objects that implement IWebhookPayload.

This is interpreted as for zope.component.registerAdapter() and may name an interface or a type.

Implementation:zope.schema.Field
Read Only:False
Required:True
Default Value:<InterfaceClass nti.webhooks.interfaces.IWebhookPayload>
when

The type of event that should result in attempted deliveries.

A type of IObjectEvent, usually one defined in zope.lifecycleevent.interfaces such as IObjectCreatedEvent. The object field of this event must provide the for_ interface; it’s the data from the object field of this event that will be sent to the webhook.

If not specified, all object events involving the for_ interface will be sent.

This must be an interface.

Implementation:nti.schema.field.Object
Read Only:False
Required:True
Default Value:<InterfaceClass zope.interface.interfaces.IObjectEvent>
Must Provide:zope.interface.interfaces.IInterface
to

The complete destination URL to which the data should be sent

This is an arbitrary HTTPS URL. Only HTTPS is supported for delivery of webhooks.

Implementation:nti.webhooks._schema.HTTPSURL
Read Only:False
Required:True
Default Value:None
Allowed Type:str
owner_id

The ID of the IPrincipal that owns this subscription.

This will be validated at runtime when an event arrives. If the current zope.security.interfaces.IAuthentication utility cannot find a principal with the given ID, the delivery will be failed.

Leave unset to disable security checks.

This cannot be changed after creation.

Implementation:nti.webhooks._schema.PermissivePrincipalId
Read Only:False
Required:False
Default Value:None
Allowed Type:str
permission_id

The ID of the permission to check

If given, and an owner is also specified, then only data that has this permission for the owner will result in an attempted delivery. If not given, but an owner is given, this will default to the standard view permission ID, zope.View.

If the permission ID cannot be found at runtime, the delivery will fail.

Implementation:nti.schema.field.ValidChoice
Read Only:False
Required:False
Default Value:None
dialect_id

The ID of the IWebhookDialect to use

Dialects are named utilities. They control the authentication, headers, and HTTP method.

Implementation:nti.schema.field.ValidChoice
Read Only:False
Required:False
Default Value:None
dialect

The resolved dialect to use for this subscription.

active

Is this webhook active? (Registered to process events.)

Determined by the subscription manager that owns this subscription.

Implementation:zope.schema.Bool
Read Only:True
Required:True
Default Value:True
Allowed Type:bool
status_message

Explanatory text about the state of this subscription.

Implementation:nti.schema.field.ValidText
Read Only:False
Required:True
Default Value:‘Active’
Allowed Type:str
__setitem__(key, value)

Add the given object to the container under the given name.

Raises a TypeError if the key is not a unicode or ascii string.

Raises a ValueError if the key is empty, or if the key contains a character which is not allowed in an object name.

Raises a KeyError if the key violates a uniqueness constraint.

The container might choose to add a different object than the one passed to this method.

If the object doesn’t implement IContained, then one of two things must be done:

  1. If the object implements ILocation, then the IContained interface must be declared for the object.
  2. Otherwise, a ContainedProxy is created for the object and stored.

The object’s __parent__ and __name__ attributes are set to the container and the given name.

If the old parent was None, then an IObjectAddedEvent is generated, otherwise, an IObjectMovedEvent is generated. An IContainerModifiedEvent is generated for the container.

If the object replaces another object, then the old object is deleted before the new object is added, unless the container vetos the replacement by raising an exception.

If the object’s __parent__ and __name__ were already set to the container and the name, then no events are generated and no hooks. This allows advanced clients to take over event generation.

isApplicable(data)

Determine if this subscription applies to the given data object.

This does not take into account whether this subscription is active or not, but does take into account the permission and principal declared for the subscription as well as the type/interface.

This is a query method that does not mutate this object.

createDeliveryAttempt(payload_data)

Create a new IWebhookDeliveryAttempt for this subscription.

The delivery attempt is in the pending status, and is stored as a child of this subscription; its __parent__ is set to this subscription.

Subscriptions may be limited in the amount of attempts they will store; this method may cause that size to temporarily be exceeded

interface nti.webhooks.interfaces.IWebhookSubscriptionManager[source]

Extends: nti.webhooks.interfaces._ITimes, nti.webhooks.interfaces.IWebhookSubscriptionRegistry, zope.container.interfaces.IContainerNamesContainer

A utility that manages subscriptions.

Also a registry for which subscriptions fire on what events.

__setitem__(key, value)

Add the given object to the container under the given name.

Raises a TypeError if the key is not a unicode or ascii string.

Raises a ValueError if the key is empty, or if the key contains a character which is not allowed in an object name.

Raises a KeyError if the key violates a uniqueness constraint.

The container might choose to add a different object than the one passed to this method.

If the object doesn’t implement IContained, then one of two things must be done:

  1. If the object implements ILocation, then the IContained interface must be declared for the object.
  2. Otherwise, a ContainedProxy is created for the object and stored.

The object’s __parent__ and __name__ attributes are set to the container and the given name.

If the old parent was None, then an IObjectAddedEvent is generated, otherwise, an IObjectMovedEvent is generated. An IContainerModifiedEvent is generated for the container.

If the object replaces another object, then the old object is deleted before the new object is added, unless the container vetos the replacement by raising an exception.

If the object’s __parent__ and __name__ were already set to the container and the name, then no events are generated and no hooks. This allows advanced clients to take over event generation.

createSubscription(to=None, for_=None, when=None, owner_id=None, permission_id=None, dialect=None)

Create and store a new IWebhookSubscription in this manager.

The new subscription is returned. It is a child of this object.

All arguments are by keyword, and have the same meaning as the attributes documented for IWebhookSubscription.

Newly created subscriptions are always active.

deactivateSubscription(subscription)

Given a subscription managed by this object, deactivate it.

activateSubscription(subscription)

Given a subscription managed by this object, activate it.

deleteSubscriptionsForPrincipal(principal_id)

Remove all subscriptions in this manager owned by principal_id.

(This is the same as the owner_id parameter to createSubscription().)

interface nti.webhooks.interfaces.IWebhookSubscriptionManagers[source]

Used as an adapter to provide an iterable of potentially interesting or related subscription managers.

See also

nti.webhooks.subscribers.remove_subscriptions_for_principal

__iter__()

Provide an iterator over IWebhookSubscriptionManagers.

interface nti.webhooks.interfaces.IWebhookSubscriptionSecuritySetter[source]

An adapter for the subscription that sets initial security declarations for a subscription.

The subscription is also passed to the call method to allow for simple functions to be used as the adapter.

In the future, the call method might also accept an event argument, and the request might be passed as a second argument to the constructor.

__call__(subscription)

Set the security declarations for the subscription.