Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more in-depth support for object lifecycle management #1318

Merged
merged 5 commits into from
Sep 27, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 79 additions & 1 deletion Storage/src/Bucket.php
Original file line number Diff line number Diff line change
Expand Up @@ -779,7 +779,7 @@ public function delete(array $options = [])
* configuration.
* @type array $defaultObjectAcl Default access controls to apply to new
* objects when no ACL is provided.
* @type array $lifecycle The bucket's lifecycle configuration.
* @type array|Lifecycle $lifecycle The bucket's lifecycle configuration.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

* @type array $logging The bucket's logging configuration, which
* defines the destination bucket and optional name prefix for the
* current bucket's logs.
Expand Down Expand Up @@ -810,6 +810,10 @@ public function delete(array $options = [])
*/
public function update(array $options = [])
{
if (isset($options['lifecycle']) && $options['lifecycle'] instanceof Lifecycle) {
$options['lifecycle'] = $options['lifecycle']->toArray();
}

return $this->info = $this->connection->patchBucket($options + $this->identity);
}

Expand Down Expand Up @@ -988,6 +992,80 @@ public function name()
return $this->identity['bucket'];
}

/**
* Retrieves a fresh lifecycle builder. If a lifecyle configuration already
* exists on the target bucket and this builder is used, it will fully
* replace the configuration with the rules provided by this builder.
*
* This builder is intended to be used in tandem with
* {@see Google\Cloud\Storage\StorageClient::createBucket()} and
* {@see Google\Cloud\Storage\Bucket::update()}.
*
* Example:
* ```
* use Google\Cloud\Storage\Bucket;
*
* $lifecycle = Bucket::lifecycle()
* ->addDeleteRule([
* 'age' => 50,
* 'isLive' => true
* ]);
* $bucket->update([
* 'lifecycle' => $lifecycle
* ]);
* ```
*
* @see https://cloud.google.com/storage/docs/lifecycle Object Lifecycle Management API Documentation
*
* @param array $lifecycle [optional] A lifecycle configuration. Please see
* [here](https://cloud.google.com/storage/docs/json_api/v1/buckets#lifecycle)
* for the expected structure.
* @return Lifecycle
*/
public static function lifecycle(array $lifecycle = [])
{
return new Lifecycle($lifecycle);
}

/**
* Retrieves a lifecycle builder preconfigured with the lifecycle rules that
* already exists on the bucket. Use this if you want to make updates to an
* existing configuration without removing existing rules, as would be the
* case when using {@see Google\Cloud\Storage\Bucket::lifecycle()}.
*
* This builder is intended to be used in tandem with
* {@see Google\Cloud\Storage\StorageClient::createBucket()} and
* {@see Google\Cloud\Storage\Bucket::update()}.
*
* Please note, this method may trigger a network request in order to fetch
* the existing lifecycle rules from the server.
*
* Example:
* ```
* $lifecycle = $bucket->currentLifecycle()
* ->addDeleteRule([
* 'age' => 50,
* 'isLive' => true
* ]);

This comment was marked as spam.

This comment was marked as spam.

* $bucket->update([
* 'lifecycle' => $lifecycle
* ]);
* ```
*
* @see https://cloud.google.com/storage/docs/lifecycle Object Lifecycle Management API Documentation
*
* @param array $options [optional] Configuration options.
* @return Lifecycle
*/
public function currentLifecycle(array $options = [])

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

{
return self::lifecycle(
isset($this->info($options)['lifecycle'])
? $this->info['lifecycle']
: []
);
}

/**
* Returns whether the bucket with the given file prefix is writable.
* Tries to create a temporary file as a resumable upload which will
Expand Down
236 changes: 236 additions & 0 deletions Storage/src/Lifecycle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
<?php
/**
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Google\Cloud\Storage;

/**
* Object Lifecycle Management supports common use cases like setting a Time to
* Live (TTL) for objects, archiving older versions of objects, or "downgrading"
* storage classes of objects to help manage costs.
*
* This builder does not execute any network requests and is intended to be used
* in combination with either
* {@see Google\Cloud\Storage\StorageClient::createBucket()}
* or {@see Google\Cloud\Storage\Bucket::update()}.
*
* Example:
* ```
* // Access a builder preconfigured with rules already existing on a given
* // bucket.
* use Google\Cloud\Storage\StorageClient;
*
* $storage = new StorageClient();
* $bucket = $storage->bucket('my-bucket');
* $lifecycle = $bucket->currentLifecycle();

This comment was marked as spam.

This comment was marked as spam.

* ```
*
* ```
* // Or get a fresh builder by using the static factory method.
* use Google\Cloud\Storage\Bucket;
*
* $lifecycle = Bucket::lifecycle();
* ```
*
* @see https://cloud.google.com/storage/docs/lifecycle Object Lifecycle Management API Documentation
*/
class Lifecycle

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

{
/**
* @var array
*/
private $lifecycle;

/**
* @param array $lifecycle [optional] A lifecycle configuration. Please see
* [here](https://cloud.google.com/storage/docs/json_api/v1/buckets#lifecycle)
* for the expected structure.
*/
public function __construct(array $lifecycle = [])
{
$this->lifecycle = $lifecycle;
}

/**
* Adds a delete rule.

This comment was marked as spam.

This comment was marked as spam.

*
* Example:
* ```
* $lifecycle->addDeleteRule([
* 'age' => 50,
* 'isLive' => true
* ]);
* ```
*
* @param array $condition {
* The condition(s) where the rule will apply.
*
* @type int $age Age of an object (in days). This condition is
* satisfied when an object reaches the specified age.
* @type string $createdBefore A date in RFC 3339 format with only the
* date part (for instance, "2013-01-15"). This condition is
* satisfied when an object is created before midnight of the
* specified date in UTC.
* @type bool $isLive Relevant only for versioned objects. If the value
* is `true`, this condition matches live objects; if the value is
* `false`, it matches archived objects.
* @type string[] $matchesStorageClass Objects having any of the storage
* classes specified by this condition will be matched. Values
* include `"MULTI_REGIONAL"`, `"REGIONAL"`, `"NEARLINE"`,
* `"COLDLINE"`, `"STANDARD"`, and `"DURABLE_REDUCED_AVAILABILITY"`.
* @type int $numNewerVersions Relevant only for versioned objects. If
* the value is N, this condition is satisfied when there are at
* least N versions (including the live version) newer than this
* version of the object.
* }
* @return Lifecycle
*/
public function addDeleteRule(array $condition)
{
$this->lifecycle['rule'][] = [
'action' => [
'type' => 'Delete'
],
'condition' => $condition
];

return $this;
}

/**
* Adds a set storage class rule.

This comment was marked as spam.

This comment was marked as spam.

*
* Example:
* ```
* $lifecycle->addSetStorageClassRule('COLDLINE', [
* 'age' => 50,
* 'isLive' => true
* ]);
* ```
*
* @param string $storageClass The target storage class. Values include
* `"MULTI_REGIONAL"`, `"REGIONAL"`, `"NEARLINE"`, `"COLDLINE"`,
* `"STANDARD"`, and `"DURABLE_REDUCED_AVAILABILITY"`.
* @param array $condition {
* The condition(s) where the rule will apply.
*
* @type int $age Age of an object (in days). This condition is
* satisfied when an object reaches the specified age.
* @type string $createdBefore A date in RFC 3339 format with only the
* date part (for instance, "2013-01-15"). This condition is
* satisfied when an object is created before midnight of the
* specified date in UTC.
* @type bool $isLive Relevant only for versioned objects. If the value
* is `true`, this condition matches live objects; if the value is
* `false`, it matches archived objects.
* @type string[] $matchesStorageClass Objects having any of the storage
* classes specified by this condition will be matched. Values
* include `"MULTI_REGIONAL"`, `"REGIONAL"`, `"NEARLINE"`,
* `"COLDLINE"`, `"STANDARD"`, and `"DURABLE_REDUCED_AVAILABILITY"`.
* @type int $numNewerVersions Relevant only for versioned objects. If
* the value is N, this condition is satisfied when there are at
* least N versions (including the live version) newer than this
* version of the object.
* }
* @return Lifecycle
*/
public function addSetStorageClassRule($storageClass, array $condition)
{
$this->lifecycle['rule'][] = [
'action' => [
'type' => 'SetStorageClass',
'storageClass' => $storageClass
],
'condition' => $condition
];

return $this;
}

/**
* Clears out rules based on the provided condition.

This comment was marked as spam.

This comment was marked as spam.

*
* Example:
* ```
* // Remove all rules.
* $lifecycle->clearRules();
* ```
*
* ```
* // Remove all "Delete" based rules.
* $lifecycle->clearRules('Delete');
* ```
*
* @param string|callable $condition [optional] If a string is provided, it
* must be the name of the type of rule to remove (`SetStorageClass`
* or `Delete`). All rules of this type will then be cleared. When
* providing a callable you may define a custom route for how you
* would like to remove rules. The provided callable will be run
* through
* [array_filter](http://php.net/manual/en/function.array-filter.php).

This comment was marked as spam.

This comment was marked as spam.

* The callable's argument will be a single lifecycle rule as an
* associative array. When returning true from the callable the rule
* will be preserved, and if false it will be removed.
* **Defaults to** `null`, clearing all assigned rules.
* @return Lifecycle
* @throws \InvalidArgumentException If a type other than a string or
* callabe is provided.
*/
public function clearRules($condition = null)

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

{
if (!$condition) {
$this->lifecycle = [];
return $this;
}

if (!is_string($condition) && !is_callable($condition)) {
throw new \InvalidArgumentException(
sprintf(
'Expected either a string or callable, instead got \'%s\'.',
gettype($condition)
)
);
}

if (isset($this->lifecycle['rule'])) {
if (is_string($condition)) {
$condition = function ($rule) use ($condition) {
return $rule['action']['type'] !== $condition;
};
}

$this->lifecycle['rule'] = array_filter(
$this->lifecycle['rule'],
$condition
);

if (!$this->lifecycle['rule']) {
$this->lifecycle = [];
}
}

return $this;
}

/**
* @access private

This comment was marked as spam.

This comment was marked as spam.

* @return array
*/
public function toArray()
{
return $this->lifecycle;
}
}
5 changes: 4 additions & 1 deletion Storage/src/StorageClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ function (array $bucket) use ($userProject) {
* configuration.
* @type array $defaultObjectAcl Default access controls to apply to new
* objects when no ACL is provided.
* @type array $lifecycle The bucket's lifecycle configuration.
* @type array|Lifecycle $lifecycle The bucket's lifecycle configuration.
* @type string $location The location of the bucket. **Defaults to**
* `"US"`.
* @type array $logging The bucket's logging configuration, which
Expand Down Expand Up @@ -306,6 +306,9 @@ public function createBucket($name, array $options = [])
'and we were unable to detect a default project ID.'
);
}
if (isset($options['lifecycle']) && $options['lifecycle'] instanceof Lifecycle) {
$options['lifecycle'] = $options['lifecycle']->toArray();
}

$bucketUserProject = $this->pluck('bucketUserProject', $options, false);
$bucketUserProject = !is_null($bucketUserProject)
Expand Down
Loading