Async/src/FuzeWorks/Async/TaskStorage/ArrayTaskStorage.php

350 lines
10 KiB
PHP

<?php
/**
* FuzeWorks Async Library
*
* The FuzeWorks PHP FrameWork
*
* Copyright (C) 2013-2020 TechFuze
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author TechFuze
* @copyright Copyright (c) 2013 - 2020, TechFuze. (http://techfuze.net)
* @license https://opensource.org/licenses/MIT MIT License
*
* @link http://techfuze.net/fuzeworks
* @since Version 1.0.0
*
* @version Version 1.0.0
*/
namespace FuzeWorks\Async\TaskStorage;
use FuzeWorks\Async\Task;
use FuzeWorks\Async\TasksException;
use FuzeWorks\Async\TaskStorage;
class ArrayTaskStorage implements TaskStorage
{
/**
* The name of the file this storage edits
*
* @var string
*/
protected $fileName;
/**
* @var array
*/
protected $data = [];
/**
* @var Task[]
*/
protected $tasks = [];
/**
* @inheritDoc
*/
public function __construct(array $parameters)
{
// Load the filename for this taskStorage
$fileName = $parameters['filename'];
if (!file_exists($fileName))
throw new TasksException("Could not construct ArrayTaskStorage. Storage file '$fileName' doesn't exist.");
if (!is_writable($fileName))
throw new TasksException("Could not construct ArrayTaskStorage. Storage file '$fileName' is not modifiable.");
$this->fileName = $fileName;
$this->refreshTasks();
}
/**
* @inheritDoc
* @throws TasksException
*/
public function addTask(Task $task): bool
{
// Check if the task doesn't exist yet
$taskId = $task->getId();
foreach ($this->tasks as $t)
{
if ($t->getId() === $taskId)
throw new TasksException("Could not add Task to TaskStorage. Task '$taskId' already exists.");
}
$this->tasks[] = $task;
$this->commit();
return true;
}
/**
* @inheritDoc
*/
public function readTasks(): array
{
return $this->tasks;
}
/**
* @inheritDoc
*/
public function refreshTasks()
{
$this->tasks = [];
$this->data = (array) include $this->fileName;
if (empty($this->data))
$this->data = ['tasks' => []];
foreach ($this->data['tasks'] as $taskString)
$this->tasks[] = unserialize($taskString);
}
/**
* @inheritDoc
* @throws TasksException
*/
public function getTaskById(string $identifier): Task
{
foreach ($this->tasks as $t)
{
if ($t->getId() === $identifier)
return $t;
}
throw new TasksException("Could not get task by Id. Task not found.");
}
/**
* @inheritDoc
* @throws TasksException
*/
public function modifyTask(Task $task): bool
{
$taskId = $task->getId();
for ($i=0;$i<count($this->tasks);$i++)
{
if ($this->tasks[$i]->getId() === $taskId)
{
$this->tasks[$i] = $task;
$this->commit();
return true;
}
}
throw new TasksException("Could not modify task. Task '$taskId' doesn't exist.");
}
/**
* @inheritDoc
* @throws TasksException
*/
public function deleteTask(Task $task): bool
{
$taskId = $task->getId();
for ($i=0;$i<count($this->tasks);$i++)
{
if ($this->tasks[$i]->getId() === $taskId)
{
// Remove the task from the main storage
unset($this->tasks[$i]);
$this->commit();
// Remove all task output and post output
$settings = $task->getSettings();
$maxRetries = $settings['maxRetries'];
for ($j=0;$j<=$maxRetries;$j++)
{
// First remove all possible task output
$outFile = dirname($this->fileName) . DS . 'task_' . md5($taskId) . '_' . $j . '_output.json';
if (file_exists($outFile))
unlink($outFile);
$postFile = dirname($this->fileName) . DS . 'task_' . md5($taskId) . '_' . $j . '_post_output.json';
if (file_exists($postFile))
unlink($postFile);
}
return true;
}
}
throw new TasksException("Could not delete task. Task '$taskId' doesn't exist.");
}
/**
* @inheritDoc
* @throws TasksException
*/
public function writeTaskOutput(Task $task, string $output, string $errors, int $statusCode, int $attempt = 0): bool
{
// Get the directory of the main storage
$dir = dirname($this->fileName);
$file = $dir . DS . 'task_' . md5($task->getId()) . '_' . $attempt . '_output.json';
$contents = json_encode(['taskId' => $task->getId(), 'output' => $output, 'errors' => $errors, 'statusCode' => $statusCode]);
// If file already exists, panic
if (file_exists($file))
throw new TasksException("Could not write task output. Output already written!");
if (!$this->write_file($file, $contents))
throw new TasksException("Could not write task output. File error.");
return true;
}
/**
* @inheritDoc
* @throws TasksException
*/
public function writePostOutput(Task $task, string $output, string $errors, int $statusCode, int $attempt = 0): bool
{
// Get the directory of the main storage
$dir = dirname($this->fileName);
$file = $dir . DS . 'task_' . md5($task->getId()) . '_' . $attempt . '_post_output.json';
$contents = json_encode(['taskId' => $task->getId(), 'output' => $output, 'errors' => $errors, 'statusCode' => $statusCode]);
// If file already exists, panic
if (file_exists($file))
throw new TasksException("Could not write task output. Output already written!");
if (!$this->write_file($file, $contents))
throw new TasksException("Could not write task output. File error.");
return true;
}
/**
* @inheritDoc
*/
public function readTaskOutput(Task $task, int $attempt = 0): ?array
{
// Get the directory of the main storage
$dir = dirname($this->fileName);
$file = $dir . DS . 'task_' . md5($task->getId()) . '_' . $attempt . '_output.json';
// If file doesn't exist, return so
if (!file_exists($file))
return null;
// Decode the contents
$contents = file_get_contents($file);
$data = json_decode($contents, true);
return ['output' => $data['output'], 'errors' => $data['errors'], 'statusCode' => $data['statusCode']];
}
/**
* @inheritDoc
*/
public function readPostOutput(Task $task, int $attempt = 0): ?array
{
// Get the directory of the main storage
$dir = dirname($this->fileName);
$file = $dir . DS . 'task_' . md5($task->getId()) . '_' . $attempt . '_post_output.json';
// If file doesn't exist, return so
if (!file_exists($file))
return null;
// Decode the contents
$contents = file_get_contents($file);
$data = json_decode($contents, true);
return ['output' => $data['output'], 'errors' => $data['errors'], 'statusCode' => $data['statusCode']];
}
/**
* @inheritDoc
* @throws TasksException
*/
public function reset(): bool
{
// Delete everything
$this->refreshTasks();
for ($i=0;$i<count($this->tasks);$i++)
{
// Get the task
$task = $this->tasks[$i];
$taskId = $task->getId();
// Remove all task output and post output
$settings = $task->getSettings();
$maxRetries = $settings['maxRetries'];
for ($j=0;$j<=$maxRetries;$j++)
{
// First remove all possible task output
$outFile = dirname($this->fileName) . DS . 'task_' . md5($taskId) . '_' . $j . '_output.json';
if (file_exists($outFile))
unlink($outFile);
$postFile = dirname($this->fileName) . DS . 'task_' . md5($taskId) . '_' . $j . '_post_output.json';
if (file_exists($postFile))
unlink($postFile);
}
// Remove the task from the main storage
unset($this->tasks[$i]);
}
// And finally commit
$this->commit();
return true;
}
private function commit()
{
$this->data = ['tasks' => []];
foreach ($this->tasks as $task)
$this->data['tasks'][] = serialize($task);
$content = var_export($this->data, true);
file_put_contents($this->fileName, "<?php return $content ;");
}
/**
* Write File
*
* Writes data to the file specified in the path.
* Creates a new file if non-existent.
*
* @param string $path File path
* @param string $data Data to write
* @param string $mode fopen() mode (default: 'wb')
* @return bool
*/
private function write_file($path, $data, $mode = 'wb')
{
if ( ! $fp = @fopen($path, $mode))
return false;
flock($fp, LOCK_EX);
for ($result = $written = 0, $length = strlen($data); $written < $length; $written += $result)
if (($result = fwrite($fp, substr($data, $written))) === false)
break;
flock($fp, LOCK_UN);
fclose($fp);
return is_int($result);
}
}