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();
$topic = $pubsub->topic('my-new-topic');
$subscription = $topic->subscription('my-new-subscription');
// Create subscription through PubSubClient
use Google\Cloud\PubSub\PubSubClient;
$pubsub = new PubSubClient();
$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 \ PubSubMethods
__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.
connection
Google\Cloud\PubSub\Connection\ConnectionInterface
The service connection object
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();
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";
}
options
array
[optional] Configuration options.
bool
create
Execute a service request creating the subscription.
The suggested way of creating a subscription is by calling through Google\Cloud\PubSub\Google\Cloud\PubSub\Topic::subscribe() or Google\Cloud\PubSub\Google\Cloud\PubSub\Topic::subscription() .
Returns subscription info in the format detailed in the documentation for a subscription .
NOTE: Some methods of instantiation of a Subscription do not supply a topic name. The topic name is required to create a subscription.
Example:
$topic = $pubsub->topic('my-new-topic');
$subscription = $topic->subscription('my-new-subscription');
$result = $subscription->create();
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\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 to7 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.
array
update
Update the subscription.
Note that subscription name and topic are immutable properties and may not be modified.
Example:
$subscription->update([
'retainAckedMessages' => true
]);
// Updating labels and push config attributes with explicit update masks.
$subscription->update([
'labels' => [
'label-1' => 'value'
],
'pushConfig' => [
'attributes' => [
'x-goog-version' => 1
]
]
], [
'updateMask' => [
'labels',
'pushConfig.attributes'
]
]);
subscription
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\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 to7 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.
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.
array
delete
Delete a subscription
Example:
$subscription->delete();
options
array
[optional] Configuration Options.
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\Google\Cloud\PubSub\Subscription::info() .
If you need to re-check the existence of a subscription that is already downloaded, call Google\Cloud\PubSub\Google\Cloud\PubSub\Subscription::reload() first to refresh the cached information.
Example:
if ($subscription->exists()) {
echo 'Subscription exists!';
}
options
array
[optional] Configuration Options
bool
info
Get info on a subscription
If the info is already cached on the object, it will return that result. To fetch a fresh result, use Google\Cloud\PubSub\Google\Cloud\PubSub\Subscription::reload() .
Example:
$info = $subscription->info();
echo $info['name']; // `projects/my-awesome-project/subscriptions/my-new-subscription`
options
array
[optional] Configuration Options
array
reload
Retrieve info on a subscription from the API.
To use the previously cached result (if it exists), use Google\Cloud\PubSub\Subscription::info() .
Example:
$subscription->reload();
$info = $subscription->info();
echo $info['name']; // `projects/my-awesome-project/subscriptions/my-new-subscription`
options
array
[optional] Configuration Options
array
pull
Retrieve new messages from the topic.
Example:
$messages = $subscription->pull();
foreach ($messages as $message) {
echo $message->data();
}
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
.
acknowledge
Acknowledge receipt of a message.
Use Google\Cloud\PubSub\Google\Cloud\PubSub\Subscription::acknowledgeBatch() to acknowledge multiple messages at once.
Example:
$messages = $subscription->pull();
foreach ($messages as $message) {
$subscription->acknowledge($message);
}
$messages = $subscription->pull();
foreach ($messages as $message) {
$failedMsgs = $subscription->acknowledge($message, ['returnFailures' => true]);
// Either log or store the $failedMsgs to be retried later
}
message
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
void|array
acknowledgeBatch
Acknowledge receipt of multiple messages at once.
Use Google\Cloud\PubSub\Google\Cloud\PubSub\Subscription::acknowledge() to acknowledge a single message.
Example:
$messages = $subscription->pull();
$subscription->acknowledgeBatch($messages);
$messages = $subscription->pull();
$failedMsgs = $subscription->acknowledgeBatch($messages, ['returnFailures' => true]);
// Either log or store the $failedMsgs to be retried later
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
void|array
modifyAckDeadline
Set the acknowledge deadline for a single ackId.
Use Google\Cloud\PubSub\Google\Cloud\PubSub\Subscription::modifyAckDeadlineBatch() to modify the ack deadline for multiple messages at once.
Example:
$messages = $subscription->pull();
foreach ($messages as $message) {
$subscription->modifyAckDeadline($message, 3);
sleep(2);
// Now we'll acknowledge!
$subscription->acknowledge($message);
break;
}
message
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
void|array
modifyAckDeadlineBatch
Set the acknowledge deadline for multiple ackIds.
Use Google\Cloud\PubSub\Google\Cloud\PubSub\Subscription::modifyAckDeadline() to modify the ack deadline for a single message.
Example:
$messages = $subscription->pull();
// Set the ack deadline to three seconds from now for every message
$subscription->modifyAckDeadlineBatch($messages, 3);
// Delay execution, or make a sandwich or something.
sleep(2);
// Now we'll acknowledge
$subscription->acknowledgeBatch($messages);
$messages = $subscription->pull();
$failedMsgs = $subscription->modifyAckDeadlineBatch($messages, 3, ['returnFailures' => true]);
// Either log or store the $failedMsgs to be retried later
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
void|array
modifyPushConfig
Set the push config for the subscription
Example:
$subscription->modifyPushConfig([
'pushEndpoint' => 'https://www.example.com/foo/bar'
]);
pushConfig
↳ 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
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);
timestamp
Google\Cloud\Core\Timestamp
The time to seek to.
options
array
[optional] Configuration options.
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);
snapshot
options
array
[optional] Configuration options.
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();
options
array
[optional] Configuration options.
array
iam
Manage the IAM policy for the current Subscription.
Example:
$iam = $subscription->iam();
Google\Cloud\Core\Iam\Iam
__debugInfo
Present a nicer debug result to people using php 5.6 or greater.
array
static::setMaxEodRetryTime
Func to change the maximum delay time for an Exactly Once Delivery
enabled subscription's
retry attempt.
maxTime
mixed
static::getMaxRetries
Getter for the private static variable
int
Constants
MAX_MESSAGES
Value: 1000