Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. <?php
  2. // reproduce datastore 409 error: too much contention on these datastore entities
  3. // 1. run: php datastore409.php
  4. // 2. run: php datastore409.php update
  5. // 3. you will see error:
  6.  
  7. // Fatal error: Uncaught exception 'Google\Cloud\Core\Exception\ConflictException' with message '{
  8. // "error": {
  9. // "code": 409,
  10. // "message": "too much contention on these datastore entities. please try again.",
  11. // "status": "ABORTED"
  12. // }
  13. // }
  14. // Includes the autoloader for libraries installed with composer
  15. require __DIR__ . '/vendor/autoload.php';
  16.  
  17. // Imports the Google Cloud client library
  18. use Google\Cloud\Datastore\DatastoreClient;
  19.  
  20. // Instantiates a client
  21. $datastore = new DatastoreClient([
  22. 'keyFilePath' => __DIR__ . '/config/gcloud_key.json',
  23. 'namespaceId' => 'test',
  24. ]);
  25.  
  26.  
  27. if (count($argv) == 1) {
  28. // The kind for the new entity
  29. $kind = 'Task';
  30.  
  31. // The name/ID for the new entity
  32. $name = 'sampleTask';
  33.  
  34. // The Cloud Datastore key for the new entity
  35. $taskKey = $datastore->key($kind, $name);
  36.  
  37. // Prepares the new entity
  38. $task = $datastore->entity($taskKey, ['description' => 'Buy milk']);
  39.  
  40. // Saves the entity
  41. $datastore->upsert($task);
  42.  
  43. echo 'Saved ' . $task->key() . ': ' . $task['description'] . PHP_EOL;
  44.  
  45.  
  46. $transaction = $datastore->transaction();
  47. $key = $datastore->key('Task', 'sampleTask');
  48. $task = $transaction->lookup($key);
  49. var_dump($task);
  50. echo 'now you should open another terminal and run: ' . "\n\n";
  51. echo ' php datastore409.php update' . "\n\n";
  52. echo 'then come back here to see result:' . "\n";
  53. sleep(10);
  54. $task['priority'] = 'slow' . time();
  55. try {
  56. $transaction->upsert($task);
  57. $transaction->commit();
  58. } catch (Google\Cloud\Core\Exception\ConflictException $e) {
  59. echo $e->getMessage() . "\n";
  60. $task_in_datastore = $datastore->lookup($key);
  61. echo 'datastore entity version: ' . $task_in_datastore->baseVersion() . "\n";
  62. echo 'php entity version: ' . $task->baseVersion() . "\n";
  63. echo 'your data version is older than datastore, so 409 error happened' . "\n";
  64. }
  65. } elseif (!empty($argv[1]) && $argv[1] == 'update') {
  66. $transaction = $datastore->transaction();
  67. $key = $datastore->key('Task', 'sampleTask');
  68. $task = $transaction->lookup($key);
  69. $task['priority'] = 'fast' . time();
  70. $transaction->upsert($task);
  71. $transaction->commit();
  72. echo 'I have updated the entity before you.' . "\n";
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement