Cloud PubSub Client - Class Subscription (2.2.1)

Reference documentation and code samples for the Cloud PubSub Client class Subscription.

A named resource representing the stream of messages from a single, specific topic, to be delivered to the subscribing application.

Example:

// Create subscription through a topic
use Google\Cloud\PubSub\PubSubClient;

$pubsub = new PubSubClient(['projectId' => 'my-awesome-project']);

$topic = $pubsub->topic('my-new-topic');

$subscription = $topic->subscription('my-new-subscription');
// Create subscription through PubSubClient
use Google\Cloud\PubSub\PubSubClient;

$pubsub = new PubSubClient(['projectId' => 'my-awesome-project']);

$subscription = $pubsub->subscription(
    'my-new-subscription',
    'my-new-topic'
);
// Consuming messages received via push with JWT Authentication.
use Google\Auth\AccessToken;

// Remove the `Bearer ` prefix from the token.
// If using another request manager such as Symfony HttpFoundation,
// use `Authorization` as the header name, e.g. `$request->headers->get('Authorization')`.
$jwt = explode(' ', $_SERVER['HTTP_AUTHORIZATION'])[1];

// Using the Access Token utility requires installation of the `phpseclib/phpseclib` dependency at version 2.
$accessTokenUtility = new AccessToken();
$payload = $accessTokenUtility->verify($jwt);
if (!$payload) {
    throw new \RuntimeException('Could not verify token!');
}

echo 'Authenticated using ' . $payload['email'];

Namespace

Google \ Cloud \ PubSub

Methods

__construct

Create a Subscription.

The idiomatic way to use this class is through the PubSubClient or Topic, but you can instantiate it directly as well.

Parameters
Name Description
requestHandler Google\Cloud\Core\RequestHandler
serializer Google\ApiCore\Serializer

The serializer instance to encode/decode messages.

projectId string

The current project

name string

The subscription name

topicName string

The topic name the subscription is attached to

encode bool

Whether messages are encrypted or not.

info array

[optional] Subscription info. Used to pre-populate the object.

name

Get the subscription name

Example:

echo $subscription->name();
Returns
Type Description
string

detached

Indicates whether the subscription is detached from its topic.

Detached subscriptions don't receive messages from their topic and don't retain any backlog. Pull and StreamingPull requests will return FAILED_PRECONDITION. If the subscription is a push subscription, pushes to the endpoint will not be made.

Example:

$detached = $subscription->detached();
if ($detached) {
    echo "The subscription is detached";
}
Parameter
Name Description
options array

[optional] Configuration options.

Returns
Type Description
bool

create

Parameters
Name Description
options array

Configuration Options

↳ ackDeadlineSeconds int

The maximum time after a subscriber receives a message before the subscriber should acknowledge the message.

↳ deadLetterPolicy array

A policy that specifies the conditions for dead lettering messages in this subscription. If deadLetterPolicy is not set, dead lettering is disabled. The Cloud Pub/Sub service account associated with this subscriptions's parent project (i.e., service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have permission to acknowledge messages on this subscription.

↳ deadLetterPolicy string|Topic

.deadLetterTopic The topic, or name of the topic to which dead letter messages should be published. Strings must be of format projects/{project}/topics/{topic}. The Cloud Pub/Sub service account associated with the enclosing subscription's parent project (i.e., service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have permission to publish to this topic. The operation will fail if the topic does not exist. Users should ensure that there is a subscription attached to this topic since messages published to a topic with no subscriptions are lost.

↳ deadLetterPolicy int

.maxDeliveryAttempts The maximum number of delivery attempts for any message. The value must be between 5 and 100.

↳ enableMessageOrdering bool

If true, messages published with the same orderingKey in Google\Cloud\PubSub\Message will be delivered to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise, they may be delivered in any order.

↳ expirationPolicy array

A policy that specifies the conditions for resource expiration (i.e., automatic resource deletion).

↳ expirationPolicy Duration|string

.ttl Specifies the "time-to-live" duration for an associated resource. The resource expires if it is not active for a period of ttl. The definition of "activity" depends on the type of the associated resource. The minimum and maximum allowed values for ttl depend on the type of the associated resource, as well. If ttl is not set, the associated resource never expires. If a string is provided, it should be as a duration in seconds with up to nine fractional digits, terminated by 's', e.g "3.5s".

↳ filter string

An expression written in the Pub/Sub filter language. If non-empty, then only messages whose attributes field matches the filter are delivered on this subscription. If empty, then no messages are filtered out. Filtering can only be configured at subscription creation.

↳ messageRetentionDuration Duration|string

How long to retain unacknowledged messages in the subscription's backlog, from the moment a message is published. If $retainAckedMessages is true, then this also configures the retention of acknowledged messages, and thus configures how far back in time a Seek can be done. Cannot be more than 7 days or less than 10 minutes. Defaults to 7 days.

↳ pushConfig array

.attributes Endpoint configuration attributes.

↳ pushConfig array

.oidcToken If specified, Pub/Sub will generate and attach an OIDC JWT token as an Authorization header in the HTTP request for every pushed message.

↳ pushConfig string

.oidcToken.audience Audience to be used when generating OIDC token. The audience claim identifies the recipients that the JWT is intended for. The audience value is a single case-sensitive string. Having multiple values (array) for the audience field is not supported. More info about the OIDC JWT token audience here: https://tools.ietf.org/html/rfc7519#section-4.1.3 Note: if not specified, the Push endpoint URL will be used.

↳ pushConfig string

.oidcToken.serviceAccountEmail Service account email to be used for generating the OIDC token. The caller (for subscriptions.create, UpdateSubscription, and subscriptions.modifyPushConfig RPCs) must have the iam.serviceAccounts.actAs permission for the service account.

↳ pushConfig string

.pushEndpoint A URL locating the endpoint to which messages should be pushed. For example, a Webhook endpoint might use "https://example.com/push".

↳ retainAckedMessages bool

Indicates whether to retain acknowledged messages.

↳ retryPolicy array

A policy that specifies how Cloud Pub/Sub retries message delivery for this subscription. If not set, the default retry policy is applied. This generally means that messages will be retried as soon as possible for healthy subscribers. Retry Policy will be triggered on NACKs or acknowledgement deadline exceeded events for a given message. Retry Policies are implemented on a best effort basis At times, the delay between deliveries may not match the configuration. That is, the delay can be more or less than the configured backoff.

↳ retryPolicy Duration|string

.minimumBackoff The minimum delay between consecutive deliveries of a given message. Value should be between 0 and 600 seconds. Defaults to 10 seconds.

↳ retryPolicy Duration|string

.maximumBackoff The maximum delay between consecutive deliveries of a given message. Value should be between 0 and 600 seconds. Defaults to 600 seconds.

↳ enableExactlyOnceDelivery bool

Indicates whether to enable 'Exactly Once Delivery' on the subscription.

↳ cloudStorageConfig array

If provided, messages will be delivered to Google Cloud Storage.

↳ cloudStorageConfig string

.bucket User-provided name for the Cloud Storage bucket. The bucket must be created by the user. The bucket name must be without any prefix like "gs://". See the bucket naming requirements.

↳ cloudStorageConfig string

.filenamePrefix User-provided prefix for Cloud Storage filename. See the object naming requirements.

↳ cloudStorageConfig string

.filenameSuffix User-provided suffix for Cloud Storage filename. See the object naming requirements. Must not end in "/".

↳ cloudStorageConfig array

.textConfig If present, payloads will be written to Cloud Storage as raw text, separated by a newline.

↳ cloudStorageConfig array

.avroConfig If set, message payloads and metadata will be written to Cloud Storage in Avro format.

↳ cloudStorageConfig bool

.avroConfig.writeMetadata When true, write the subscription name, message_id, publish_time, attributes, and ordering_key as additional fields in the output.

↳ cloudStorageConfig Duration|string

.maxDuration The maximum duration that can elapse before a new Cloud Storage file is created. Min 1 minute, max 10 minutes, default 5 minutes. May not exceed the subscription's acknowledgement deadline. If a string is provided, it should be as a duration in seconds with up to nine fractional digits, terminated by 's', e.g "3.5s"

↳ cloudStorageConfig int|string

.maxBytes The maximum bytes that can be written to a Cloud Storage file before a new file is created. Min 1 KB, max 10 GiB. The max_bytes limit may be exceeded in cases where messages are larger than the limit.

Returns
Type Description
array An array of subscription info

update

Parameters
Name Description
data array

The Subscription data.

↳ ackDeadlineSeconds int

The maximum time after a subscriber receives a message before the subscriber should acknowledge the message.

↳ deadLetterPolicy array

A policy that specifies the conditions for dead lettering messages in this subscription. If deadLetterPolicy is not set, dead lettering is disabled. The Cloud Pub/Sub service account associated with this subscriptions's parent project (i.e., service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have permission to acknowledge messages on this subscription.

↳ deadLetterPolicy string|Topic

.deadLetterTopic The topic, or name of the topic to which dead letter messages should be published. Strings must be of format projects/{project}/topics/{topic}. The Cloud Pub/Sub service account associated with the enclosing subscription's parent project (i.e., service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have permission to publish to this topic. The operation will fail if the topic does not exist. Users should ensure that there is a subscription attached to this topic since messages published to a topic with no subscriptions are lost.

↳ deadLetterPolicy int

.maxDeliveryAttempts The maximum number of delivery attempts for any message. The value must be between 5 and 100.

↳ enableMessageOrdering bool

If true, messages published with the same orderingKey in Google\Cloud\PubSub\Message will be delivered to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise, they may be delivered in any order.

↳ expirationPolicy array

A policy that specifies the conditions for resource expiration (i.e., automatic resource deletion).

↳ expirationPolicy Duration|string

.ttl Specifies the "time-to-live" duration for an associated resource. The resource expires if it is not active for a period of ttl. The definition of "activity" depends on the type of the associated resource. The minimum and maximum allowed values for ttl depend on the type of the associated resource, as well. If ttl is not set, the associated resource never expires. If a string is provided, it should be as a duration in seconds with up to nine fractional digits, terminated by 's', e.g "3.5s".

↳ messageRetentionDuration Duration|string

How long to retain unacknowledged messages in the subscription's backlog, from the moment a message is published. If $retainAckedMessages is true, then this also configures the retention of acknowledged messages, and thus configures how far back in time a Seek can be done. Cannot be more than 7 days or less than 10 minutes. Defaults to 7 days.

↳ pushConfig array

.attributes Endpoint configuration attributes.

↳ pushConfig array

.oidcToken If specified, Pub/Sub will generate and attach an OIDC JWT token as an Authorization header in the HTTP request for every pushed message.

↳ pushConfig string

.oidcToken.audience Audience to be used when generating OIDC token. The audience claim identifies the recipients that the JWT is intended for. The audience value is a single case-sensitive string. Having multiple values (array) for the audience field is not supported. More info about the OIDC JWT token audience here: https://tools.ietf.org/html/rfc7519#section-4.1.3 Note: if not specified, the Push endpoint URL will be used.

↳ pushConfig string

.oidcToken.serviceAccountEmail Service account email to be used for generating the OIDC token. The caller (for subscriptions.create, UpdateSubscription, and subscriptions.modifyPushConfig RPCs) must have the iam.serviceAccounts.actAs permission for the service account.

↳ pushConfig string

.pushEndpoint A URL locating the endpoint to which messages should be pushed. For example, a Webhook endpoint might use "https://example.com/push".

↳ retainAckedMessages bool

Indicates whether to retain acknowledged messages.

↳ retryPolicy array

A policy that specifies how Cloud Pub/Sub retries message delivery for this subscription. If not set, the default retry policy is applied. This generally means that messages will be retried as soon as possible for healthy subscribers. Retry Policy will be triggered on NACKs or acknowledgement deadline exceeded events for a given message. Retry Policies are implemented on a best effort basis At times, the delay between deliveries may not match the configuration. That is, the delay can be more or less than the configured backoff.

↳ retryPolicy Duration|string

.minimumBackoff The minimum delay between consecutive deliveries of a given message. Value should be between 0 and 600 seconds. Defaults to 10 seconds.

↳ retryPolicy Duration|string

.maximumBackoff The maximum delay between consecutive deliveries of a given message. Value should be between 0 and 600 seconds. Defaults to 600 seconds.

↳ enableExactlyOnceDelivery bool

Indicates whether to enable 'Exactly Once Delivery' on the subscription.

↳ cloudStorageConfig array

If provided, messages will be delivered to Google Cloud Storage.

↳ cloudStorageConfig string

.bucket User-provided name for the Cloud Storage bucket. The bucket must be created by the user. The bucket name must be without any prefix like "gs://". See the bucket naming requirements.

↳ cloudStorageConfig string

.filenamePrefix User-provided prefix for Cloud Storage filename. See the object naming requirements.

↳ cloudStorageConfig string

.filenameSuffix User-provided suffix for Cloud Storage filename. See the object naming requirements. Must not end in "/".

↳ cloudStorageConfig array

.textConfig If present, payloads will be written to Cloud Storage as raw text, separated by a newline.

↳ cloudStorageConfig array

.avroConfig If set, message payloads and metadata will be written to Cloud Storage in Avro format.

↳ cloudStorageConfig bool

.avroConfig.writeMetadata When true, write the subscription name, message_id, publish_time, attributes, and ordering_key as additional fields in the output.

↳ cloudStorageConfig Duration|string

.maxDuration The maximum duration that can elapse before a new Cloud Storage file is created. Min 1 minute, max 10 minutes, default 5 minutes. May not exceed the subscription's acknowledgement deadline. If a string is provided, it should be as a duration in seconds with up to nine fractional digits, terminated by 's', e.g "3.5s"

↳ cloudStorageConfig int|string

.maxBytes The maximum bytes that can be written to a Cloud Storage file before a new file is created. Min 1 KB, max 10 GiB. The max_bytes limit may be exceeded in cases where messages are larger than the limit.

options array

Configuration options.

↳ updateMask array

A list of field paths to be modified. Nested key names should be dot-separated, e.g. pushConfig.pushEndpoint. Google Cloud PHP will attempt to infer this value on your behalf, however modification of map fields with arbitrary keys (such as labels or push config attributes) requires an explicit update mask.

Returns
Type Description
array The subscription info.

delete

Parameter
Name Description
options array

[optional] Configuration Options.

Returns
Type Description
void

exists

Check if a subscription exists.

Service errors will NOT bubble up from this method. It will always return a boolean value. If you want to check for errors, use Google\Cloud\PubSub\Subscription::info().

If you need to re-check the existence of a subscription that is already downloaded, call Google\Cloud\PubSub\Subscription::reload() first to refresh the cached information.

Example:

if ($subscription->exists()) {
    echo 'Subscription exists!';
}
Parameter
Name Description
options array

[optional] Configuration Options

Returns
Type Description
bool

info

See also:

Parameter
Name Description
options array

[optional] Configuration Options

Returns
Type Description
array Subscription data

reload

See also:

Parameter
Name Description
options array

[optional] Configuration Options

Returns
Type Description
array Subscription data

pull

Parameters
Name Description
options array

Configuration Options

↳ returnImmediately bool

If true, the system will respond immediately, even if no messages are available. Otherwise, wait until new messages are available. Defaults to false.

↳ maxMessages int

Limit the amount of messages pulled. Defaults to 1000.

Returns
Type Description
array<Google\Cloud\PubSub\Message>

acknowledge

Parameters
Name Description
message Google\Cloud\PubSub\Message

A message object.

options array

Configuration Options

↳ returnFailures bool

If set, and if an acknowledgement is failed with a temporary failure code, it will be retried with an exponential delay. This will also make sure that the permanently failed message is returned to the caller. This is only true for a subscription with 'Exactly Once Delivery' enabled. Read more about EOD: https://cloud.google.com/pubsub/docs/exactly-once-delivery

Returns
Type Description
void|array

acknowledgeBatch

Parameters
Name Description
messages array<Google\Cloud\PubSub\Message>

An array of messages

options array

Configuration Options

↳ returnFailures bool

If set, and if a message is failed with a temporary failure code, it will be retried with an exponential delay. This will also make sure that the permanently failed message is returned to the caller. This is only true for a subscription with 'Exactly Once Delivery' enabled. Read more about EOD: https://cloud.google.com/pubsub/docs/exactly-once-delivery

Returns
Type Description
void|array

modifyAckDeadline

Parameters
Name Description
message Google\Cloud\PubSub\Message

A message object

seconds int

The new ack deadline with respect to the time this request was sent to the Pub/Sub system. Must be >= 0. For example, if the value is 10, the new ack deadline will expire 10 seconds after the ModifyAckDeadline call was made. Specifying zero may immediately make the message available for another pull request.

options array

Configuration Options

↳ returnFailures bool

If set, and if a message is failed with a temporary failure code, it will be retried with an exponential delay. This will also make sure that the permanently failed message is returned to the caller. This is only true for a subscription with 'Exactly Once Delivery' enabled. Read more about EOD: https://cloud.google.com/pubsub/docs/exactly-once-delivery

Returns
Type Description
void|array

modifyAckDeadlineBatch

Parameters
Name Description
messages array<Google\Cloud\PubSub\Message>

An array of messages

seconds int

The new ack deadline with respect to the time this request was sent to the Pub/Sub system. Must be >= 0. For example, if the value is 10, the new ack deadline will expire 10 seconds after the ModifyAckDeadline call was made. Specifying zero may immediately make the message available for another pull request.

options array

Configuration Options

↳ returnFailures bool

If set, and if a message is failed with a temporary failure code, it will be retried with an exponential delay. This will also make sure that the permanently failed message is returned to the caller. This is only true for a subscription with 'Exactly Once Delivery' enabled. Read more about EOD: https://cloud.google.com/pubsub/docs/exactly-once-delivery

Returns
Type Description
void|array

modifyPushConfig

Parameters
Name Description
pushConfig array

Push delivery configuration. See PushConfig for more details.

↳ pushEndpoint string

A URL locating the endpoint to which messages should be pushed. For example, a Webhook endpoint might use "https://example.com/push".

↳ attributes array

Endpoint configuration attributes.

options array

[optional] Configuration Options

Returns
Type Description
void

seekToTime

Seek to a given timestamp.

When you seek to a time, it has the effect of marking every message received before this time as acknowledged, and all messages received after the time as unacknowledged.

Please note that this method may not yet be available in your project.

Example:

$time = $pubsub->timestamp(new \DateTime('2017-04-01'));
$subscription->seekToTime($time);
Parameters
Name Description
timestamp Google\Cloud\Core\Timestamp

The time to seek to.

options array

[optional] Configuration options.

Returns
Type Description
void

seekToSnapshot

Seek to a given snapshot.

When seeking to a snapshot, any message that had an "unacknowledged" state when the snapshot was created can be re-delivered.

Please note that this method may not yet be available in your project.

Example:

$snapshot = $pubsub->snapshot('my-snapshot');
$subscription->seekToSnapshot($snapshot);
Parameters
Name Description
snapshot Google\Cloud\PubSub\Snapshot

The snapshot to seek to.

options array

[optional] Configuration options.

Returns
Type Description
void

detach

Detach the subscription from its topic.

All messages retained in the subscription are dropped. Subsequent Pull requests will return FAILED_PRECONDITION. If the subscription is a push subscription, pushes to the endpoint will stop.

Example:

$subscription->detach();
Parameter
Name Description
options array

[optional] Configuration options.

Returns
Type Description
array

iam

Returns
Type Description
Google\Cloud\Core\Iam\IamManager

__debugInfo

Present a nicer debug result to people using php 5.6 or greater.

Returns
Type Description
array

static::setMaxEodRetryTime

Func to change the maximum delay time for an Exactly Once Delivery enabled subscription's retry attempt.

Parameter
Name Description
maxTime mixed

static::getMaxRetries

Getter for the private static variable

Returns
Type Description
int

Constants

MAX_MESSAGES

Value: 1000