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 \ 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.
requestHandler
Google\Cloud\Core\RequestHandler
serializer
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
See also:
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.
deadLetterTopic
string|Topic
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.
maxDeliveryAttempts
int
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 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).
ttl
Duration|string
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.attributes
array
Endpoint configuration attributes.
↳ pushConfig.oidcToken
array
If specified, Pub/Sub will generate and attach an OIDC JWT token as an Authorization
header in the HTTP request for every pushed message.
audience
string
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.
serviceAccountEmail
string
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.pushEndpoint
string
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.
minimumBackoff
Duration|string
The minimum delay between consecutive deliveries of a given message. Value should be between 0 and 600 seconds. Defaults to 10 seconds.
maximumBackoff
Duration|string
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.
bucket
string
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 .
filenamePrefix
filenameSuffix
string
User-provided suffix for Cloud Storage filename. See the object naming requirements . Must not end in "/".
textConfig
array
If present, payloads will be written to Cloud Storage as raw text, separated by a newline.
avroConfig
array
If set, message payloads and metadata will be written to Cloud Storage in Avro format.
maxDuration
Duration|string
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"
maxBytes
int|string
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.
array
update
See also:
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.
deadLetterTopic
string|Topic
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.
maxDeliveryAttempts
int
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 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).
ttl
Duration|string
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.attributes
array
Endpoint configuration attributes.
↳ pushConfig.oidcToken
array
If specified, Pub/Sub will generate and attach an OIDC JWT token as an Authorization
header in the HTTP request for every pushed message.
audience
string
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.
serviceAccountEmail
string
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.pushEndpoint
string
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.
minimumBackoff
Duration|string
The minimum delay between consecutive deliveries of a given message. Value should be between 0 and 600 seconds. Defaults to 10 seconds.
maximumBackoff
Duration|string
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.
bucket
string
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 .
filenamePrefix
filenameSuffix
string
User-provided suffix for Cloud Storage filename. See the object naming requirements . Must not end in "/".
textConfig
array
If present, payloads will be written to Cloud Storage as raw text, separated by a newline.
avroConfig
array
If set, message payloads and metadata will be written to Cloud Storage in Avro format.
maxDuration
Duration|string
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"
maxBytes
int|string
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.
array
delete
See also:
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 Subscription::info() .
If you need to re-check the existence of a subscription that is already downloaded, call Subscription::reload() first to refresh the cached information.
Example:
if ($subscription->exists()) {
echo 'Subscription exists!';
}
options
array
[optional] Configuration Options
bool
info
See also:
options
array
[optional] Configuration Options
array
reload
See also:
options
array
[optional] Configuration Options
array
pull
See also:
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
See also:
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
See also:
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
See also:
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
See also:
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
See also:
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
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
See also:
Google\Cloud\Core\Iam\IamManager
__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