diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c71ec7..3ca915c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,58 @@ # Changelog -All notable changes to Makhzan are documented here. +All notable changes to Storely are documented here. + +## v0.7.0 - 2026-12-04 + +### Changed (breaking) - renamed from Makhzan + +The package is now **Storely**. Behaviour, API shape and design are unchanged; every public name changed. + +| Before (v0.6.0) | After (v0.7.0) | +| --- | --- | +| `elbanbydev/makhzan` | `elbanbydev/storely` | +| namespace `Makhzan\` | `Storely\` | +| `Makhzan` facade, `MakhzanServiceProvider` | `Storely`, `StorelyServiceProvider` | +| `MakhzanFile`, `MakhzanSpace`, `MakhzanFileLocation`, `MakhzanMove`, `MakhzanRoutingRule` | `StorelyFile`, `StorelySpace`, `StorelyFileLocation`, `StorelyMove`, `StorelyRoutingRule` | +| `MakhzanException` | `StorelyException` | +| `config/makhzan.php`, config key `makhzan.*` | `config/storely.php`, config key `storely.*` | +| `MAKHZAN_MAX_UPLOAD_BYTES`, `MAKHZAN_CAPACITY_WARNING_PERCENT`, `MAKHZAN_QUEUE`, `MAKHZAN_LOCAL_ROOT` | `STORELY_*` equivalents | +| publish tags `makhzan-config`, `makhzan-migrations` | `storely-config`, `storely-migrations` | +| tables `makhzan_spaces`, `makhzan_files`, `makhzan_file_locations`, `makhzan_moves`, `makhzan_routing_rules` | `storely_*` | +| commands `makhzan:usage`, `makhzan:health`, `makhzan:verify`, `makhzan:prune`, `makhzan:gc`, `makhzan:replicate` | `storely:*` | +| default local root `storage/app/makhzan` | `storage/app/storely` | + +### Upgrading from v0.6.0 + +Nothing about how the package works changed, so the upgrade is mechanical. Do it in one deploy. + +1. **Swap the package.** `composer remove elbanbydev/makhzan && composer require elbanbydev/storely:^0.7` +2. **Rename in your code.** `Makhzan\` -> `Storely\` everywhere (classes, events, exceptions, jobs), and the facade import `use Makhzan\Facades\Makhzan;` -> `use Storely\Facades\Storely;`. A find-and-replace on `Makhzan` -> `Storely` covers it. +3. **Config and env.** Rename `config/makhzan.php` to `config/storely.php` (or republish: `php artisan vendor:publish --tag=storely-config --force`) and change `config('makhzan.*')` calls to `config('storely.*')`. Rename the four `MAKHZAN_*` env vars to `STORELY_*` in `.env`. +4. **Rename the tables (keeps your data) and relabel the migration rows** so `php artisan migrate` treats the new migrations as already applied: + +```sql +RENAME TABLE makhzan_spaces TO storely_spaces, + makhzan_files TO storely_files, + makhzan_file_locations TO storely_file_locations, + makhzan_moves TO storely_moves, + makhzan_routing_rules TO storely_routing_rules; + +UPDATE migrations SET migration = REPLACE(migration, 'makhzan', 'storely') +WHERE migration LIKE '%makhzan%'; +``` + +5. **Published migrations.** If you published the package migrations, delete the four `*_create_makhzan_*_table.php` files (the SQL above already relabelled their `migrations` rows, so the new `*_create_storely_*` files will not run). +6. **Local space files.** If you use `local` driver spaces, `mv storage/app/makhzan storage/app/storely`, or set `STORELY_LOCAL_ROOT=app/makhzan` to keep the old path. +7. **Drain the queue first.** Serialized `Makhzan\Jobs\MirrorFileJob` / `MoveLocationJob` payloads cannot be unserialized once the classes are gone. Let mirror and drain jobs finish before you deploy. +8. **Scheduler.** Point scheduled commands at `storely:*` instead of `makhzan:*`. +9. **Clear caches.** `php artisan config:clear && php artisan cache:clear`. ## v0.6.0 - 2026-12-03 ### Added -- Restore: `Makhzan::restore($file)` undoes a soft delete; it throws when every copy is already gone. Restoring a live file is a no-op. -- `makhzan:replicate `: copies every file on one space to another, SHA-256 verified, source untouched; existing copies are skipped and failures are listed per file (non-zero exit when any fail). +- Restore: `Storely::restore($file)` undoes a soft delete; it throws when every copy is already gone. Restoring a live file is a no-op. +- `storely:replicate `: copies every file on one space to another, SHA-256 verified, source untouched; existing copies are skipped and failures are listed per file (non-zero exit when any fail). ### Docs - Refreshed the package description (composer.json + GitHub) and the README (EN + AR) feature overview so the public face reflects everything through v0.6.0: routing rules, temporary URLs, integrity verification, lifecycle commands and replication. @@ -14,15 +60,15 @@ All notable changes to Makhzan are documented here. ## v0.5.0 - 2026-12-03 ### Added -- Temporary URLs: `Makhzan::temporaryUrl($file, $minutes)` returns a short-lived signed URL from the first live copy whose driver supports it (new `SupportsTemporaryUrls` contract, implemented by the Flysystem/S3-family driver). Drivers that cannot sign are skipped; a failed signing attempt falls through to the next copy; minutes are clamped to 1..10080. -- Garbage collection: `makhzan:gc` removes location rows on deleted spaces and reports files left with zero copies; `--check-remote` also drops locations whose copy is confirmed gone from its space (unreachable spaces are kept), `--purge` deletes the empty file records, `--dry-run` reports only. Backed by `GcService` and `Makhzan::gc()`. +- Temporary URLs: `Storely::temporaryUrl($file, $minutes)` returns a short-lived signed URL from the first live copy whose driver supports it (new `SupportsTemporaryUrls` contract, implemented by the Flysystem/S3-family driver). Drivers that cannot sign are skipped; a failed signing attempt falls through to the next copy; minutes are clamped to 1..10080. +- Garbage collection: `storely:gc` removes location rows on deleted spaces and reports files left with zero copies; `--check-remote` also drops locations whose copy is confirmed gone from its space (unreachable spaces are kept), `--purge` deletes the empty file records, `--dry-run` reports only. Backed by `GcService` and `Storely::gc()`. ## v0.4.0 - 2026-12-03 ### Added -- Routing rules: steer files to a space by category and optional size range. Active rules are evaluated by ascending priority and add their spaces to the write candidates before the plain fill order; a rule with an optional per-rule mirror; broken rules (missing/full/failing space) fall through. `RuleService` with validated create/update/delete, `Makhzan::rules()`, and `Makhzan::store(..., $category)`. -- File deletion: `Makhzan::delete()` soft-deletes a file (copies stay), `Makhzan::forceDelete()` removes every copy from its space before deleting the record. -- `makhzan:prune` command: force-deletes files soft-deleted longer than `--days` (default 30), with `--dry-run`. +- Routing rules: steer files to a space by category and optional size range. Active rules are evaluated by ascending priority and add their spaces to the write candidates before the plain fill order; a rule with an optional per-rule mirror; broken rules (missing/full/failing space) fall through. `RuleService` with validated create/update/delete, `Storely::rules()`, and `Storely::store(..., $category)`. +- File deletion: `Storely::delete()` soft-deletes a file (copies stay), `Storely::forceDelete()` removes every copy from its space before deleting the record. +- `storely:prune` command: force-deletes files soft-deleted longer than `--days` (default 30), with `--dry-run`. ## v0.3.1 - 2026-12-03 @@ -32,7 +78,7 @@ All notable changes to Makhzan are documented here. ## v0.3.0 - 2026-12-03 ### Added -- `makhzan:verify` command: walks every recorded copy (optionally one space), checks it still exists on its space, refreshes `verified_at`, lists missing/unreachable copies and exits non-zero when any are found. +- `storely:verify` command: walks every recorded copy (optionally one space), checks it still exists on its space, refreshes `verified_at`, lists missing/unreachable copies and exits non-zero when any are found. ## v0.2.0 - 2026-12-03 @@ -47,4 +93,4 @@ All notable changes to Makhzan are documented here. ## v0.1.0 - 2026-12-03 ### Added -- First public cut: storage spaces (local, R2, B2, generic S3, Google Drive, Telegram) with encrypted credentials, priority fill order, live health checks with test gating, automatic write/read failover, per-space usage with capacity warnings, mirroring, background drains, content-addressed dedup, `makhzan:health` and `makhzan:usage` commands, EN + AR docs. +- First public cut: storage spaces (local, R2, B2, generic S3, Google Drive, Telegram) with encrypted credentials, priority fill order, live health checks with test gating, automatic write/read failover, per-space usage with capacity warnings, mirroring, background drains, content-addressed dedup, `storely:health` and `storely:usage` commands, EN + AR docs. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7ff3af7..fe2475b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,7 +15,7 @@ All three gates must pass before a PR. Add tests for every behavior change. - `declare(strict_types=1)` in every PHP file. - Credentials and secrets are never logged, serialized, or returned by the API. -- Driver errors are wrapped in `MakhzanException` with a message that never includes credentials or tokens. +- Driver errors are wrapped in `StorelyException` with a message that never includes credentials or tokens. - Database changes come with a new migration; published migrations are never edited. ## Reporting security issues diff --git a/README.md b/README.md index 4d4fdb7..d9cea43 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,32 @@ -# Makhzan (مخزن) +# Storely + +[![CI](https://github.com/elbanbydev/storely/actions/workflows/ci.yml/badge.svg)](https://github.com/elbanbydev/storely/actions/workflows/ci.yml) +[![Latest release](https://img.shields.io/github/v/release/elbanbydev/storely?sort=semver)](https://github.com/elbanbydev/storely/releases) +[![PHP](https://img.shields.io/badge/php-8.2%2B-blue)](composer.json) +[![License](https://img.shields.io/github/license/elbanbydev/storely)](LICENSE.md) **Organize your Laravel app's storage spaces.** Register every storage space your site uses — local disks, Cloudflare R2, Backblaze B2, any S3-compatible bucket, Google Drive, Telegram — behind one content-addressed store with per-space priorities, category routing rules, usage visibility, live health checks, automatic failover, capacity warnings, mirroring, safe background drains, bulk replication, temporary URLs, integrity verification and a full file lifecycle (delete, restore, prune, garbage collection). [التوثيق بالعربية](docs/ar/README.md) > **Status:** experimental (pre-1.0). The API may change between minor versions until v1.0. +> +> **Renamed:** this package was called **Makhzan** through v0.6.0. Same code, same design, new name: `Makhzan\` is now `Storely\`, `elbanbydev/makhzan` is now `elbanbydev/storely`, tables are `storely_*`, commands are `storely:*`. The upgrade steps (including the table rename SQL) are in the [changelog](CHANGELOG.md#upgrading-from-v060). ## Why -A growing site rarely has one disk. It has a free R2 bucket, a B2 bucket for overflow, a Drive folder from the team account, a Telegram channel for small files — and no idea which one is full or down. Makhzan turns that pile into an organized system: +A growing site rarely has one disk. It has a free R2 bucket, a B2 bucket for overflow, a Drive folder from the team account, a Telegram channel for small files — and no idea which one is full or down. Storely turns that pile into an organized system: - **Priorities** — each space has a fill order; new files go to the first space that can take them. -- **Usage visibility** — files, bytes and percent of declared capacity per space, in code or with `php artisan makhzan:usage`. +- **Usage visibility** — files, bytes and percent of declared capacity per space, in code or with `php artisan storely:usage`. - **Health checks** — a live write/read/delete round trip per space, on demand or scheduled; a space only serves files after passing on its *current* credentials. -- **Automatic failover** — if a write fails, Makhzan tries the next candidate and tells you (event). Reads fail over across a file's copies. +- **Automatic failover** — if a write fails, Storely tries the next candidate and tells you (event). Reads fail over across a file's copies. - **Capacity warnings** — an event the moment a space crosses the warning line (default 80%). - **Routing rules** — steer files to a space by category and size, with per-rule mirrors; anything unmatched follows the plain fill order. -- **Mirroring, drains & replication** — mirror every write to a second space, empty a space into another in the background with a progress record, or bulk-copy a space onto another with `php artisan makhzan:replicate`. +- **Mirroring, drains & replication** — mirror every write to a second space, empty a space into another in the background with a progress record, or bulk-copy a space onto another with `php artisan storely:replicate`. - **Content addressing** — identical bytes are stored once (SHA-256 + size), copies are verified by hash. - **Temporary URLs** — short-lived signed URLs from S3-family spaces, with graceful fallback across a file's copies. -- **Integrity & lifecycle** — `makhzan:verify` confirms every recorded copy still exists; delete/restore keeps files recoverable, `makhzan:prune` clears old soft deletes, `makhzan:gc` drops rows pointing at storage that no longer exists. +- **Integrity & lifecycle** — `storely:verify` confirms every recorded copy still exists; delete/restore keeps files recoverable, `storely:prune` clears old soft deletes, `storely:gc` drops rows pointing at storage that no longer exists. ## Requirements @@ -29,24 +36,24 @@ A growing site rarely has one disk. It has a free R2 bucket, a B2 bucket for ove ## Install ```bash -composer require elbanbydev/makhzan +composer require elbanbydev/storely php artisan migrate ``` Optionally publish the config: ```bash -php artisan vendor:publish --tag=makhzan-config +php artisan vendor:publish --tag=storely-config ``` ## Quick start ```php -use Makhzan\Enums\SpaceDriver; -use Makhzan\Facades\Makhzan; +use Storely\Enums\SpaceDriver; +use Storely\Facades\Storely; // 1. Register a space. Credentials are encrypted at rest and never returned. -$r2 = Makhzan::addSpace('R2 main', SpaceDriver::R2, [ +$r2 = Storely::addSpace('R2 main', SpaceDriver::R2, [ 'account_id' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'bucket' => 'my-bucket', 'access_key' => '...', @@ -54,15 +61,15 @@ $r2 = Makhzan::addSpace('R2 main', SpaceDriver::R2, [ ], priority: 10, capacityBytes: 10 * 1024 ** 3); // 2. Run the live check, then activate. Activation without a passing check is refused. -Makhzan::spaces()->check($r2); -Makhzan::spaces()->setStatus($r2, \Makhzan\Enums\SpaceStatus::Active); +Storely::spaces()->check($r2); +Storely::spaces()->setStatus($r2, \Storely\Enums\SpaceStatus::Active); // 3. Store and read. Writes follow the fill order with failover; reads fail over across copies. -$file = Makhzan::store($stream, 'lecture.pdf', 'application/pdf'); -$contents = stream_get_contents(Makhzan::read($file)['stream']); +$file = Storely::store($stream, 'lecture.pdf', 'application/pdf'); +$contents = stream_get_contents(Storely::read($file)['stream']); // 4. See usage per space. -foreach (Makhzan::usage() as $spaceId => $u) { +foreach (Storely::usage() as $spaceId => $u) { // $u = ['files' => 12, 'bytes' => 458752, 'percent' => 4, 'warning' => false] } ``` @@ -71,7 +78,7 @@ foreach (Makhzan::usage() as $spaceId => $u) { ### Spaces and statuses -A **space** (`makhzan_spaces`) is one storage account: a driver plus encrypted credentials, a priority, an optional declared capacity, and a status: +A **space** (`storely_spaces`) is one storage account: a driver plus encrypted credentials, a priority, an optional declared capacity, and a status: | Status | Serves reads | Accepts writes | | --- | --- | --- | @@ -84,92 +91,92 @@ A space can only leave `disabled` after `check()` passes on its exact current cr ### Fill order and failover -Writes go to the first space that is active, has a passing check, has declared capacity left, and whose driver accepts the file size (Telegram caps at 20 MB). If the write throws, Makhzan dispatches `SpaceFailover` and tries the next candidate. If nothing can take the file: `NoUsableSpaceException`; if every candidate tried and failed: `AllSpacesFailedException` with the per-space reasons. +Writes go to the first space that is active, has a passing check, has declared capacity left, and whose driver accepts the file size (Telegram caps at 20 MB). If the write throws, Storely dispatches `SpaceFailover` and tries the next candidate. If nothing can take the file: `NoUsableSpaceException`; if every candidate tried and failed: `AllSpacesFailedException` with the per-space reasons. ### Routing rules -Rules steer files to a space by category and size. `Makhzan::store()` takes a category (default `general`): +Rules steer files to a space by category and size. `Storely::store()` takes a category (default `general`): ```php -Makhzan::store($stream, 'invoice.pdf', 'application/pdf', 'invoices'); +Storely::store($stream, 'invoice.pdf', 'application/pdf', 'invoices'); -Makhzan::rules()->create([ +Storely::rules()->create([ 'name' => 'Invoices to R2', 'category' => 'invoices', // 'any' matches every category 'min_size' => null, // bytes, optional 'max_size' => 5 * 1024 * 1024, // bytes, optional - 'makhzan_space_id' => $r2->id, + 'storely_space_id' => $r2->id, 'mirror_space_id' => $b2->id, // optional per-rule mirror 'priority' => 10, // lower runs first ]); ``` -Active rules are evaluated by ascending priority; every matching rule adds its space to the write candidates, then spaces no rule claims follow in plain fill order. A rule whose space is gone, full or failing its check falls through to the next one. Update or remove rules with `Makhzan::rules()->update($rule, [...])` and `->delete($rule)`. +Active rules are evaluated by ascending priority; every matching rule adds its space to the write candidates, then spaces no rule claims follow in plain fill order. A rule whose space is gone, full or failing its check falls through to the next one. Update or remove rules with `Storely::rules()->update($rule, [...])` and `->delete($rule)`. ### Temporary URLs S3-family spaces (R2, B2, S3) can hand out short-lived signed URLs to a stored copy: ```php -$url = Makhzan::temporaryUrl($file, 10); // valid 10 minutes, null when no copy can sign +$url = Storely::temporaryUrl($file, 10); // valid 10 minutes, null when no copy can sign ``` -Makhzan picks the first live copy (in fill order) whose driver supports signing; drivers that cannot (local, Google Drive, Telegram) are skipped, and a copy that fails to sign falls through to the next. Minutes are clamped to 1..10080. +Storely picks the first live copy (in fill order) whose driver supports signing; drivers that cannot (local, Google Drive, Telegram) are skipped, and a copy that fails to sign falls through to the next. Minutes are clamped to 1..10080. ### Deleting files ```php -Makhzan::delete($file); // soft delete; copies stay on their spaces -Makhzan::restore($file); // undo a soft delete (throws when no copy is left) -Makhzan::forceDelete($file); // remove every copy from its space, then the record +Storely::delete($file); // soft delete; copies stay on their spaces +Storely::restore($file); // undo a soft delete (throws when no copy is left) +Storely::forceDelete($file); // remove every copy from its space, then the record ``` Copy every file from one space onto another without touching the source (each new copy is SHA-256 verified): ```bash -php artisan makhzan:replicate 1 2 # from space 1 to space 2 +php artisan storely:replicate 1 2 # from space 1 to space 2 ``` ```bash -php artisan makhzan:prune # force-delete files soft-deleted 30+ days ago -php artisan makhzan:prune --days=7 -php artisan makhzan:prune --dry-run # list what would go, delete nothing +php artisan storely:prune # force-delete files soft-deleted 30+ days ago +php artisan storely:prune --days=7 +php artisan storely:prune --dry-run # list what would go, delete nothing ``` ### Garbage collection -Over time the database can point at storage that no longer exists: a space was deleted while files still had copies on it, or someone removed objects on the provider side. `makhzan:gc` cleans those rows: +Over time the database can point at storage that no longer exists: a space was deleted while files still had copies on it, or someone removed objects on the provider side. `storely:gc` cleans those rows: ```bash -php artisan makhzan:gc # drop locations on deleted spaces, report files left with no copies -php artisan makhzan:gc --check-remote # also ask every space whether each copy still exists -php artisan makhzan:gc --purge # also delete file records left with zero copies -php artisan makhzan:gc --dry-run # report only, remove nothing +php artisan storely:gc # drop locations on deleted spaces, report files left with no copies +php artisan storely:gc --check-remote # also ask every space whether each copy still exists +php artisan storely:gc --purge # also delete file records left with zero copies +php artisan storely:gc --dry-run # report only, remove nothing ``` -A copy on an unreachable space is kept; health checks own that signal. Use `makhzan:verify` to refresh `verified_at` on copies that do exist. +A copy on an unreachable space is kept; health checks own that signal. Use `storely:verify` to refresh `verified_at` on copies that do exist. ### Health checks ```php -Makhzan::health()->check($space); // one space -Makhzan::health()->checkAll(); // every space -Makhzan::health()->unhealthy(); // serving spaces whose check no longer matches +Storely::health()->check($space); // one space +Storely::health()->checkAll(); // every space +Storely::health()->unhealthy(); // serving spaces whose check no longer matches ``` ```bash -php artisan makhzan:health # all spaces, non-zero exit on failure -php artisan makhzan:health --space=3 # one space -php artisan makhzan:verify # every recorded copy still exists on its space -php artisan makhzan:verify --space=3 # one space +php artisan storely:health # all spaces, non-zero exit on failure +php artisan storely:health --space=3 # one space +php artisan storely:verify # every recorded copy still exists on its space +php artisan storely:verify --space=3 # one space ``` -`makhzan:verify` walks the recorded locations, confirms each copy still exists on its space, refreshes `verified_at`, and lists missing or unreachable copies (non-zero exit when any). +`storely:verify` walks the recorded locations, confirms each copy still exists on its space, refreshes `verified_at`, and lists missing or unreachable copies (non-zero exit when any). Schedule it in `routes/console.php` (or `app/Console/Kernel.php` on Laravel 11): ```php -Schedule::command('makhzan:health')->hourly(); +Schedule::command('storely:health')->hourly(); ``` A failing check disables the space (writes skip it immediately) and fires `SpaceChecked`. @@ -179,21 +186,21 @@ A failing check disables the space (writes skip it immediately) and fires `Space Set `capacity_bytes` on a space and listen: ```php -use Makhzan\Events\SpaceCapacityWarning; +use Storely\Events\SpaceCapacityWarning; Event::listen(SpaceCapacityWarning::class, function (SpaceCapacityWarning $e) { // $e->space, $e->usedBytes, $e->capacityBytes, $e->percent }); ``` -The event fires once when usage *crosses* the configured percent (`MAKHZAN_CAPACITY_WARNING_PERCENT`, default 80), not on every write above it. +The event fires once when usage *crosses* the configured percent (`STORELY_CAPACITY_WARNING_PERCENT`, default 80), not on every write above it. ### Mirroring Attach a mirror space and every new write is copied to it by a queued job: ```php -Makhzan::spaces()->setMirror($main, $backup); +Storely::spaces()->setMirror($main, $backup); ``` ### Draining a space @@ -201,7 +208,7 @@ Makhzan::spaces()->setMirror($main, $backup); To retire a space, empty it into another one in the background: ```php -$move = Makhzan::drain($from, $to); // queued MakhzanMove with total/done/failed +$move = Storely::drain($from, $to); // queued StorelyMove with total/done/failed ``` The source becomes `draining` (reads keep working, writes stop), each copy is moved only after the new one is verified by SHA-256, and when the drain finishes clean the source is parked as `disabled`. `MoveCompleted` fires at the end. @@ -227,18 +234,18 @@ Each driver's `fields()` describes its credential fields (label, secret, require - Credentials are stored with Laravel's `encrypted:array` cast and are excluded from serialization (`$hidden`); the raw DB value is ciphertext. - A space serves files only while its stored credentials match the ones that passed the live check. -- URLs must be `https://` domain names (no IPs); the local root is restricted to a safe directory name under `storage/app/makhzan`. +- URLs must be `https://` domain names (no IPs); the local root is restricted to a safe directory name under `storage/app/storely`. - Stored file names are reduced to a safe basename. -- Makhzan performs **no authorization**: anyone who can call `Makhzan::spaces()` can manage spaces. Gate these calls in your own admin panel (policy, middleware, or permission) exactly like you gate any other admin action. +- Storely performs **no authorization**: anyone who can call `Storely::spaces()` can manage spaces. Gate these calls in your own admin panel (policy, middleware, or permission) exactly like you gate any other admin action. ## Configuration | Key | Env | Default | Purpose | | --- | --- | --- | --- | -| `max_upload_bytes` | `MAKHZAN_MAX_UPLOAD_BYTES` | 512 MB | per-file upload ceiling | -| `capacity_warning_percent` | `MAKHZAN_CAPACITY_WARNING_PERCENT` | 80 | warning line | -| `queue` | `MAKHZAN_QUEUE` | default | queue for mirror/drain jobs | -| `local_root` | `MAKHZAN_LOCAL_ROOT` | `app/makhzan` | where `local` spaces live, under `storage_path()` | +| `max_upload_bytes` | `STORELY_MAX_UPLOAD_BYTES` | 512 MB | per-file upload ceiling | +| `capacity_warning_percent` | `STORELY_CAPACITY_WARNING_PERCENT` | 80 | warning line | +| `queue` | `STORELY_QUEUE` | default | queue for mirror/drain jobs | +| `local_root` | `STORELY_LOCAL_ROOT` | `app/storely` | where `local` spaces live, under `storage_path()` | ## Testing diff --git a/SECURITY.md b/SECURITY.md index 00357b3..8c6e449 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,7 +2,7 @@ ## Supported versions -Makhzan is pre-1.0; only the latest release receives security fixes. +Storely is pre-1.0; only the latest release receives security fixes. ## Reporting a vulnerability @@ -12,4 +12,4 @@ Email **ahmed@elbanby.com** with the details and a reproduction if possible. Do - Space credentials are stored encrypted with your `APP_KEY`. Rotate the credentials if the key ever leaks. - The `local` driver is for development; it stores files under your app's `storage/` directory. -- Makhzan does not authorize calls. Gate space management behind your own admin authorization. +- Storely does not authorize calls. Gate space management behind your own admin authorization. diff --git a/composer.json b/composer.json index b747acb..9020430 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { - "name": "elbanbydev/makhzan", - "description": "Makhzan (مخزن) - organize your Laravel app's storage spaces (local, S3-compatible like Cloudflare R2 and Backblaze B2, Google Drive, Telegram) behind one content-addressed store with per-space priorities, category routing rules, usage visibility, health checks, automatic failover, capacity warnings, mirroring, safe background drains, bulk replication, temporary URLs, integrity verification and a full file lifecycle. Experimental.", + "name": "elbanbydev/storely", + "description": "Storely - organize your Laravel app's storage spaces (local, S3-compatible like Cloudflare R2 and Backblaze B2, Google Drive, Telegram) behind one content-addressed store with per-space priorities, category routing rules, usage visibility, health checks, automatic failover, capacity warnings, mirroring, safe background drains, bulk replication, temporary URLs, integrity verification and a full file lifecycle. Experimental.", "keywords": [ "laravel", "storage", @@ -11,7 +11,7 @@ "s3", "failover", "storage-priority", - "makhzan" + "storely" ], "license": "MIT", "require": { @@ -35,12 +35,12 @@ }, "autoload": { "psr-4": { - "Makhzan\\": "src/" + "Storely\\": "src/" } }, "autoload-dev": { "psr-4": { - "Makhzan\\Tests\\": "tests/" + "Storely\\Tests\\": "tests/" }, "files": [ "tests/Support/helpers.php" @@ -49,10 +49,10 @@ "extra": { "laravel": { "providers": [ - "Makhzan\\MakhzanServiceProvider" + "Storely\\StorelyServiceProvider" ], "aliases": { - "Makhzan": "Makhzan\\Facades\\Makhzan" + "Storely": "Storely\\Facades\\Storely" } } }, diff --git a/config/makhzan.php b/config/storely.php similarity index 68% rename from config/makhzan.php rename to config/storely.php index 21e0a51..feebbb2 100644 --- a/config/makhzan.php +++ b/config/storely.php @@ -6,21 +6,21 @@ /* | Maximum size of a single stored file, in bytes (default 512 MB). */ - 'max_upload_bytes' => (int) env('MAKHZAN_MAX_UPLOAD_BYTES', 512 * 1024 * 1024), + 'max_upload_bytes' => (int) env('STORELY_MAX_UPLOAD_BYTES', 512 * 1024 * 1024), /* | A SpaceCapacityWarning event fires when a space's used bytes cross this | percent of its declared capacity. */ - 'capacity_warning_percent' => (int) env('MAKHZAN_CAPACITY_WARNING_PERCENT', 80), + 'capacity_warning_percent' => (int) env('STORELY_CAPACITY_WARNING_PERCENT', 80), /* | Queue used by mirror and drain jobs. Null = the app's default connection. */ - 'queue' => env('MAKHZAN_QUEUE'), + 'queue' => env('STORELY_QUEUE'), /* | Root directory for `local` driver spaces, relative to storage_path(). */ - 'local_root' => env('MAKHZAN_LOCAL_ROOT', 'app/makhzan'), + 'local_root' => env('STORELY_LOCAL_ROOT', 'app/storely'), ]; diff --git a/database/migrations/2026_01_01_000001_create_makhzan_spaces_table.php b/database/migrations/2026_01_01_000001_create_storely_spaces_table.php similarity index 90% rename from database/migrations/2026_01_01_000001_create_makhzan_spaces_table.php rename to database/migrations/2026_01_01_000001_create_storely_spaces_table.php index 926b772..e7afb19 100644 --- a/database/migrations/2026_01_01_000001_create_makhzan_spaces_table.php +++ b/database/migrations/2026_01_01_000001_create_storely_spaces_table.php @@ -10,7 +10,7 @@ { public function up(): void { - Schema::create('makhzan_spaces', function (Blueprint $table) { + Schema::create('storely_spaces', function (Blueprint $table) { $table->id(); $table->string('name', 100); $table->string('driver', 20); @@ -31,12 +31,12 @@ public function up(): void $table->softDeletes(); $table->index(['status', 'priority']); - $table->foreign('mirror_space_id')->references('id')->on('makhzan_spaces')->nullOnDelete(); + $table->foreign('mirror_space_id')->references('id')->on('storely_spaces')->nullOnDelete(); }); } public function down(): void { - Schema::dropIfExists('makhzan_spaces'); + Schema::dropIfExists('storely_spaces'); } }; diff --git a/database/migrations/2026_01_01_000002_create_makhzan_files_tables.php b/database/migrations/2026_01_01_000002_create_storely_files_tables.php similarity index 59% rename from database/migrations/2026_01_01_000002_create_makhzan_files_tables.php rename to database/migrations/2026_01_01_000002_create_storely_files_tables.php index 95d73b0..b01a1e6 100644 --- a/database/migrations/2026_01_01_000002_create_makhzan_files_tables.php +++ b/database/migrations/2026_01_01_000002_create_storely_files_tables.php @@ -10,7 +10,7 @@ { public function up(): void { - Schema::create('makhzan_files', function (Blueprint $table) { + Schema::create('storely_files', function (Blueprint $table) { $table->id(); // Content address: identical bytes (same sha256 + size) are stored once. $table->string('sha256', 64); @@ -23,10 +23,10 @@ public function up(): void $table->unique(['sha256', 'size']); }); - Schema::create('makhzan_file_locations', function (Blueprint $table) { + Schema::create('storely_file_locations', function (Blueprint $table) { $table->id(); - $table->unsignedBigInteger('makhzan_file_id'); - $table->unsignedBigInteger('makhzan_space_id'); + $table->unsignedBigInteger('storely_file_id'); + $table->unsignedBigInteger('storely_space_id'); // Driver-specific handle: object key, Drive file id, or ":". $table->text('locator'); $table->string('role', 10)->default('primary'); @@ -34,16 +34,16 @@ public function up(): void $table->timestamps(); $table->softDeletes(); - $table->unique(['makhzan_file_id', 'makhzan_space_id', 'deleted_at'], 'makhzan_location_unique'); - $table->index(['makhzan_space_id', 'deleted_at']); - $table->foreign('makhzan_file_id')->references('id')->on('makhzan_files')->cascadeOnDelete(); - $table->foreign('makhzan_space_id')->references('id')->on('makhzan_spaces')->cascadeOnDelete(); + $table->unique(['storely_file_id', 'storely_space_id', 'deleted_at'], 'storely_location_unique'); + $table->index(['storely_space_id', 'deleted_at']); + $table->foreign('storely_file_id')->references('id')->on('storely_files')->cascadeOnDelete(); + $table->foreign('storely_space_id')->references('id')->on('storely_spaces')->cascadeOnDelete(); }); } public function down(): void { - Schema::dropIfExists('makhzan_file_locations'); - Schema::dropIfExists('makhzan_files'); + Schema::dropIfExists('storely_file_locations'); + Schema::dropIfExists('storely_files'); } }; diff --git a/database/migrations/2026_01_01_000003_create_makhzan_moves_table.php b/database/migrations/2026_01_01_000003_create_storely_moves_table.php similarity index 85% rename from database/migrations/2026_01_01_000003_create_makhzan_moves_table.php rename to database/migrations/2026_01_01_000003_create_storely_moves_table.php index 55731f4..0638fe0 100644 --- a/database/migrations/2026_01_01_000003_create_makhzan_moves_table.php +++ b/database/migrations/2026_01_01_000003_create_storely_moves_table.php @@ -10,7 +10,7 @@ { public function up(): void { - Schema::create('makhzan_moves', function (Blueprint $table) { + Schema::create('storely_moves', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('from_space_id'); $table->unsignedBigInteger('to_space_id'); @@ -24,13 +24,13 @@ public function up(): void $table->softDeletes(); $table->index(['status']); - $table->foreign('from_space_id')->references('id')->on('makhzan_spaces')->cascadeOnDelete(); - $table->foreign('to_space_id')->references('id')->on('makhzan_spaces')->cascadeOnDelete(); + $table->foreign('from_space_id')->references('id')->on('storely_spaces')->cascadeOnDelete(); + $table->foreign('to_space_id')->references('id')->on('storely_spaces')->cascadeOnDelete(); }); } public function down(): void { - Schema::dropIfExists('makhzan_moves'); + Schema::dropIfExists('storely_moves'); } }; diff --git a/database/migrations/2026_01_01_000004_create_makhzan_routing_rules_table.php b/database/migrations/2026_01_01_000004_create_storely_routing_rules_table.php similarity index 76% rename from database/migrations/2026_01_01_000004_create_makhzan_routing_rules_table.php rename to database/migrations/2026_01_01_000004_create_storely_routing_rules_table.php index 1e5324c..613887d 100644 --- a/database/migrations/2026_01_01_000004_create_makhzan_routing_rules_table.php +++ b/database/migrations/2026_01_01_000004_create_storely_routing_rules_table.php @@ -10,7 +10,7 @@ { public function up(): void { - Schema::create('makhzan_routing_rules', function (Blueprint $table) { + Schema::create('storely_routing_rules', function (Blueprint $table) { $table->id(); $table->string('name', 100); // Lower number is evaluated first. @@ -19,20 +19,20 @@ public function up(): void $table->string('category', 50)->default('any'); $table->unsignedBigInteger('min_size')->nullable(); $table->unsignedBigInteger('max_size')->nullable(); - $table->unsignedBigInteger('makhzan_space_id'); + $table->unsignedBigInteger('storely_space_id'); $table->unsignedBigInteger('mirror_space_id')->nullable(); $table->boolean('is_active')->default(true); $table->timestamps(); $table->softDeletes(); $table->index(['is_active', 'priority']); - $table->foreign('makhzan_space_id')->references('id')->on('makhzan_spaces')->cascadeOnDelete(); - $table->foreign('mirror_space_id')->references('id')->on('makhzan_spaces')->nullOnDelete(); + $table->foreign('storely_space_id')->references('id')->on('storely_spaces')->cascadeOnDelete(); + $table->foreign('mirror_space_id')->references('id')->on('storely_spaces')->nullOnDelete(); }); } public function down(): void { - Schema::dropIfExists('makhzan_routing_rules'); + Schema::dropIfExists('storely_routing_rules'); } }; diff --git a/docs/ar/README.md b/docs/ar/README.md index 4003777..9c1f952 100644 --- a/docs/ar/README.md +++ b/docs/ar/README.md @@ -1,23 +1,25 @@ -# مخزن (Makhzan) +# Storely (ستورلي) **نظّم مساحات التخزين في موقعك.** سجّل كل مساحات التخزين التي يستخدمها موقعك — أقراص محلية، Cloudflare R2، Backblaze B2، أي Bucket متوافق مع S3، Google Drive، تليجرام — خلف مخزن واحد يعتمد بصمة المحتوى، مع أولويات لكل مساحة، وقواعد توجيه حسب التصنيف، ورؤية واضحة للاستخدام، وفحوصات صحية حية، وتحويل تلقائي عند الفشل، وتنبيهات امتلاء، ونسخ احتياطي (Mirror)، وتفريغ آمن في الخلفية، ونسخ جماعي بين المساحات، وروابط مؤقتة، وتحقق من سلامة النسخ، ودورة حياة كاملة للملفات (حذف، استعادة، تنظيف، جمع نفايات). > **الحالة:** تجريبية (قبل 1.0). قد تتغير الواجهة البرمجية بين الإصدارات الفرعية حتى الإصدار 1.0. +> +> **تغيير الاسم:** كانت الحزمة تُسمى **Makhzan** حتى الإصدار 0.6.0. الكود والتصميم كما هما، والأسماء كلها تغيّرت: `Makhzan\` أصبح `Storely\`، و`elbanbydev/makhzan` أصبح `elbanbydev/storely`، والجداول `storely_*`، والأوامر `storely:*`. خطوات الترقية (مع SQL إعادة تسمية الجداول) في [سجل التغييرات](../CHANGELOG.md#upgrading-from-v060). ## لماذا؟ -الموقع الذي يكبر نادراً ما يكون له قرص واحد: Bucket مجاني على R2، وBucket آخر على B2 للزيادة، ومجلد Drive من حساب الفريق، وقناة تليجرام للملفات الصغيرة — ولا أحد يعرف أيها امتلأ أو تعطّل. مخزن يحوّل هذه الفوضى إلى نظام: +الموقع الذي يكبر نادراً ما يكون له قرص واحد: Bucket مجاني على R2، وBucket آخر على B2 للزيادة، ومجلد Drive من حساب الفريق، وقناة تليجرام للملفات الصغيرة — ولا أحد يعرف أيها امتلأ أو تعطّل. ستورلي يحوّل هذه الفوضى إلى نظام: - **أولويات** — لكل مساحة ترتيب تعبئة؛ الملفات الجديدة تذهب لأول مساحة تقبلها. -- **رؤية الاستخدام** — عدد الملفات والبايتات والنسبة من السعة المعلنة لكل مساحة، برمجياً أو عبر `php artisan makhzan:usage`. +- **رؤية الاستخدام** — عدد الملفات والبايتات والنسبة من السعة المعلنة لكل مساحة، برمجياً أو عبر `php artisan storely:usage`. - **فحوصات صحية** — تجربة حية (كتابة وقراءة وحذف) لكل مساحة، يدوياً أو مجدولة؛ لا تخدم المساحة الملفات إلا بعد نجاح الفحص على بياناتها الحالية. -- **تحويل تلقائي** — إذا فشلت الكتابة يجرب مخزن المساحة التالية ويخطرك (حدث). القراءة تتحول تلقائياً بين نسخ الملف. +- **تحويل تلقائي** — إذا فشلت الكتابة يجرب ستورلي المساحة التالية ويخطرك (حدث). القراءة تتحول تلقائياً بين نسخ الملف. - **تنبيهات الامتلاء** — حدث لحظة تجاوز المساحة خط التنبيه (افتراضياً 80%). - **قواعد التوجيه** — وجّه الملفات لمساحة حسب التصنيف والحجم، مع نسخة احتياطية لكل قاعدة؛ ما لا يطابق قاعدة يتبع ترتيب التعبئة العادي. -- **النسخ والتفريغ والاستنساخ** — انسخ كل كتابة إلى مساحة ثانية، فرّغ مساحة كاملة في أخرى بالخلفية مع سجل تقدم، أو انسخ مساحة بأكملها إلى أخرى عبر `php artisan makhzan:replicate`. +- **النسخ والتفريغ والاستنساخ** — انسخ كل كتابة إلى مساحة ثانية، فرّغ مساحة كاملة في أخرى بالخلفية مع سجل تقدم، أو انسخ مساحة بأكملها إلى أخرى عبر `php artisan storely:replicate`. - **بصمة المحتوى** — المحتوى المتطابق يخزَّن مرة واحدة (SHA-256 + الحجم)، والنسخ تتحقق بالبصمة. - **روابط مؤقتة** — روابط موقَّعة قصيرة العمر من مساحات عائلة S3، مع تراجع تلقائي بين نسخ الملف. -- **السلامة ودورة الحياة** — `makhzan:verify` يؤكد أن كل نسخة مسجلة ما زالت موجودة؛ الحذف والاستعادة يبقيان الملفات قابلة للاسترجاع، `makhzan:prune` ينظف المحذوفات المؤقتة القديمة، و`makhzan:gc` يزيل الصفوف التي تشير إلى تخزين لم يعد موجوداً. +- **السلامة ودورة الحياة** — `storely:verify` يؤكد أن كل نسخة مسجلة ما زالت موجودة؛ الحذف والاستعادة يبقيان الملفات قابلة للاسترجاع، `storely:prune` ينظف المحذوفات المؤقتة القديمة، و`storely:gc` يزيل الصفوف التي تشير إلى تخزين لم يعد موجوداً. ## المتطلبات @@ -27,24 +29,24 @@ ## التثبيت ```bash -composer require elbanbydev/makhzan +composer require elbanbydev/storely php artisan migrate ``` ولنشر ملف الإعدادات اختيارياً: ```bash -php artisan vendor:publish --tag=makhzan-config +php artisan vendor:publish --tag=storely-config ``` ## البدء السريع ```php -use Makhzan\Enums\SpaceDriver; -use Makhzan\Facades\Makhzan; +use Storely\Enums\SpaceDriver; +use Storely\Facades\Storely; // 1. سجّل مساحة. البيانات السرية تُشفَّر في قاعدة البيانات ولا تُعاد أبداً. -$r2 = Makhzan::addSpace('R2 الرئيسي', SpaceDriver::R2, [ +$r2 = Storely::addSpace('R2 الرئيسي', SpaceDriver::R2, [ 'account_id' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'bucket' => 'my-bucket', 'access_key' => '...', @@ -52,15 +54,15 @@ $r2 = Makhzan::addSpace('R2 الرئيسي', SpaceDriver::R2, [ ], priority: 10, capacityBytes: 10 * 1024 ** 3); // 2. شغّل الفحص الحي ثم فعّل المساحة. التفعيل بدون فحص ناجح مرفوض. -Makhzan::spaces()->check($r2); -Makhzan::spaces()->setStatus($r2, \Makhzan\Enums\SpaceStatus::Active); +Storely::spaces()->check($r2); +Storely::spaces()->setStatus($r2, \Storely\Enums\SpaceStatus::Active); // 3. خزّن واقرأ. الكتابة تتبع ترتيب التعبئة مع تحويل تلقائي، والقراءة تتحول بين النسخ. -$file = Makhzan::store($stream, 'lecture.pdf', 'application/pdf'); -$contents = stream_get_contents(Makhzan::read($file)['stream']); +$file = Storely::store($stream, 'lecture.pdf', 'application/pdf'); +$contents = stream_get_contents(Storely::read($file)['stream']); // 4. اعرض الاستخدام لكل مساحة. -foreach (Makhzan::usage() as $spaceId => $u) { +foreach (Storely::usage() as $spaceId => $u) { // $u = ['files' => 12, 'bytes' => 458752, 'percent' => 4, 'warning' => false] } ``` @@ -69,7 +71,7 @@ foreach (Makhzan::usage() as $spaceId => $u) { ### المساحات وحالاتها -**المساحة** (`makhzan_spaces`) هي حساب تخزين واحد: درايفر + بيانات سرية مشفرة، وأولوية، وسعة معلنة اختيارية، وحالة: +**المساحة** (`storely_spaces`) هي حساب تخزين واحد: درايفر + بيانات سرية مشفرة، وأولوية، وسعة معلنة اختيارية، وحالة: | الحالة | تخدم القراءة | تقبل الكتابة | | --- | --- | --- | @@ -82,92 +84,92 @@ foreach (Makhzan::usage() as $spaceId => $u) { ### ترتيب التعبئة والتحويل التلقائي -تذهب الكتابة لأول مساحة نشطة، ناجحة الفحص، لديها سعة متبقية، ويقبل درايفرها حجم الملف (تليجرام بحد أقصى 20 ميجابايت). إذا فشلت الكتابة يطلق مخزن حدث `SpaceFailover` ويجرب المرشح التالي. إذا لم تقبل أي مساحة الملف: `NoUsableSpaceException`؛ وإذا فشلت كل المرشحين: `AllSpacesFailedException` مع سبب الفشل لكل مساحة. +تذهب الكتابة لأول مساحة نشطة، ناجحة الفحص، لديها سعة متبقية، ويقبل درايفرها حجم الملف (تليجرام بحد أقصى 20 ميجابايت). إذا فشلت الكتابة يطلق ستورلي حدث `SpaceFailover` ويجرب المرشح التالي. إذا لم تقبل أي مساحة الملف: `NoUsableSpaceException`؛ وإذا فشلت كل المرشحين: `AllSpacesFailedException` مع سبب الفشل لكل مساحة. ### قواعد التوجيه -القواعد توجه الملفات لمساحة معينة حسب التصنيف والحجم. `Makhzan::store()` يقبل تصنيفاً (افتراضياً `general`): +القواعد توجه الملفات لمساحة معينة حسب التصنيف والحجم. `Storely::store()` يقبل تصنيفاً (افتراضياً `general`): ```php -Makhzan::store($stream, 'invoice.pdf', 'application/pdf', 'invoices'); +Storely::store($stream, 'invoice.pdf', 'application/pdf', 'invoices'); -Makhzan::rules()->create([ +Storely::rules()->create([ 'name' => 'الفواتير إلى R2', 'category' => 'invoices', // 'any' تطابق كل التصنيفات 'min_size' => null, // بالبايت، اختياري 'max_size' => 5 * 1024 * 1024, // بالبايت، اختياري - 'makhzan_space_id' => $r2->id, + 'storely_space_id' => $r2->id, 'mirror_space_id' => $b2->id, // نسخة احتياطية اختيارية خاصة بالقاعدة 'priority' => 10, // الأقل يعمل أولاً ]); ``` -تُقيَّم القواعد النشطة حسب الأولوية التصاعدية؛ كل قاعدة مطابقة تضيف مساحتها لمرشحي الكتابة، ثم تتبعها المساحات التي لا تطالب بها أي قاعدة بترتيب التعبئة العادي. القاعدة التي مساحتها محذوفة أو ممتلئة أو راسبة الفحص يتم تجاوزها للقاعدة التالية. للتحديث أو الحذف: `Makhzan::rules()->update($rule, [...])` و `->delete($rule)`. +تُقيَّم القواعد النشطة حسب الأولوية التصاعدية؛ كل قاعدة مطابقة تضيف مساحتها لمرشحي الكتابة، ثم تتبعها المساحات التي لا تطالب بها أي قاعدة بترتيب التعبئة العادي. القاعدة التي مساحتها محذوفة أو ممتلئة أو راسبة الفحص يتم تجاوزها للقاعدة التالية. للتحديث أو الحذف: `Storely::rules()->update($rule, [...])` و `->delete($rule)`. ### روابط مؤقتة مساحات عائلة S3 (R2 وB2 وS3) تستطيع إصدار روابط موقَّعة قصيرة العمر لنسخة مخزنة: ```php -$url = Makhzan::temporaryUrl($file, 10); // صالح 10 دقائق، أو null إذا لم تستطع أي نسخة التوقيع +$url = Storely::temporaryUrl($file, 10); // صالح 10 دقائق، أو null إذا لم تستطع أي نسخة التوقيع ``` -يختار مخزن أول نسخة حية (بترتيب التعبئة) درايفرها يدعم التوقيع؛ الدرايفرات غير القادرة (المحلي، جوجل درايف، تليجرام) يتم تجاوزها، والنسخة التي يفشل توقيعها يسقط إلى النسخة التالية. الدقائق محصورة بين 1 و10080. +يختار ستورلي أول نسخة حية (بترتيب التعبئة) درايفرها يدعم التوقيع؛ الدرايفرات غير القادرة (المحلي، جوجل درايف، تليجرام) يتم تجاوزها، والنسخة التي يفشل توقيعها يسقط إلى النسخة التالية. الدقائق محصورة بين 1 و10080. ### حذف الملفات ```php -Makhzan::delete($file); // حذف مؤقت؛ تبقى النسخ على مساحاتها -Makhzan::restore($file); // تراجع عن الحذف المؤقت (يرمي استثناء إذا لم تبق أي نسخة) -Makhzan::forceDelete($file); // حذف كل نسخة من مساحتها ثم السجل +Storely::delete($file); // حذف مؤقت؛ تبقى النسخ على مساحاتها +Storely::restore($file); // تراجع عن الحذف المؤقت (يرمي استثناء إذا لم تبق أي نسخة) +Storely::forceDelete($file); // حذف كل نسخة من مساحتها ثم السجل ``` نسخ كل ملف من مساحة إلى أخرى دون المساس بالمصدر (كل نسخة جديدة تتحقق بـ SHA-256): ```bash -php artisan makhzan:replicate 1 2 // من المساحة 1 إلى المساحة 2 +php artisan storely:replicate 1 2 // من المساحة 1 إلى المساحة 2 ``` ```bash -php artisan makhzan:prune // حذف نهائي للملفات المحذوفة مؤقتاً منذ 30+ يوماً -php artisan makhzan:prune --days=7 -php artisan makhzan:prune --dry-run // عرض ما سيُحذف دون حذف +php artisan storely:prune // حذف نهائي للملفات المحذوفة مؤقتاً منذ 30+ يوماً +php artisan storely:prune --days=7 +php artisan storely:prune --dry-run // عرض ما سيُحذف دون حذف ``` ### جمع النفايات -مع الوقت قد تشير قاعدة البيانات إلى تخزين لم يعد موجوداً: مساحة حُذفت وما زالت عليها نسخ، أو أحد حذف عناصر من جهة المزود. أمر `makhzan:gc` ينظف هذه الصفوف: +مع الوقت قد تشير قاعدة البيانات إلى تخزين لم يعد موجوداً: مساحة حُذفت وما زالت عليها نسخ، أو أحد حذف عناصر من جهة المزود. أمر `storely:gc` ينظف هذه الصفوف: ```bash -php artisan makhzan:gc // حذف مواقع على مساحات محذوفة، والإبلاغ عن ملفات بلا نسخ -php artisan makhzan:gc --check-remote // سؤال كل مساحة أيضاً عما إذا كانت كل نسخة ما زالت موجودة -php artisan makhzan:gc --purge // حذف سجلات الملفات التي لم يبق لها أي نسخة -php artisan makhzan:gc --dry-run // تقرير فقط دون حذف +php artisan storely:gc // حذف مواقع على مساحات محذوفة، والإبلاغ عن ملفات بلا نسخ +php artisan storely:gc --check-remote // سؤال كل مساحة أيضاً عما إذا كانت كل نسخة ما زالت موجودة +php artisan storely:gc --purge // حذف سجلات الملفات التي لم يبق لها أي نسخة +php artisan storely:gc --dry-run // تقرير فقط دون حذف ``` -النسخة على مساحة لا يمكن الوصول إليها تُترك كما هي؛ الفحوصات الصحية مسؤولة عن تلك الإشارة. استخدم `makhzan:verify` لتحديث `verified_at` للنسخ الموجودة فعلاً. +النسخة على مساحة لا يمكن الوصول إليها تُترك كما هي؛ الفحوصات الصحية مسؤولة عن تلك الإشارة. استخدم `storely:verify` لتحديث `verified_at` للنسخ الموجودة فعلاً. ### الفحوصات الصحية ```php -Makhzan::health()->check($space); // مساحة واحدة -Makhzan::health()->checkAll(); // كل المساحات -Makhzan::health()->unhealthy(); // المساحات العاملة التي لم يعد فحصها مطابقاً +Storely::health()->check($space); // مساحة واحدة +Storely::health()->checkAll(); // كل المساحات +Storely::health()->unhealthy(); // المساحات العاملة التي لم يعد فحصها مطابقاً ``` ```bash -php artisan makhzan:health # كل المساحات، ورمز خروج غير صفري عند الفشل -php artisan makhzan:health --space=3 # مساحة واحدة -php artisan makhzan:verify # التحقق أن كل نسخة مسجلة ما زالت موجودة في مساحتها -php artisan makhzan:verify --space=3 # مساحة واحدة +php artisan storely:health # كل المساحات، ورمز خروج غير صفري عند الفشل +php artisan storely:health --space=3 # مساحة واحدة +php artisan storely:verify # التحقق أن كل نسخة مسجلة ما زالت موجودة في مساحتها +php artisan storely:verify --space=3 # مساحة واحدة ``` -أمر `makhzan:verify` يمر على النسخ المسجلة ويتأكد أن كل نسخة ما زالت موجودة في مساحتها، ويحدّث `verified_at`، ويعرض النسخ المفقودة أو المساحات التي تعذّر الوصول إليها (رمز خروج غير صفري عند وجود أي منها). +أمر `storely:verify` يمر على النسخ المسجلة ويتأكد أن كل نسخة ما زالت موجودة في مساحتها، ويحدّث `verified_at`، ويعرض النسخ المفقودة أو المساحات التي تعذّر الوصول إليها (رمز خروج غير صفري عند وجود أي منها). اجدوله في `routes/console.php` (أو `app/Console/Kernel.php` في Laravel 11): ```php -Schedule::command('makhzan:health')->hourly(); +Schedule::command('storely:health')->hourly(); ``` الفحص الفاشل يعطّل المساحة (تتخطاها الكتابات فوراً) ويطلق حدث `SpaceChecked`. @@ -177,21 +179,21 @@ Schedule::command('makhzan:health')->hourly(); عيّن `capacity_bytes` للمساحة واستمع للحدث: ```php -use Makhzan\Events\SpaceCapacityWarning; +use Storely\Events\SpaceCapacityWarning; Event::listen(SpaceCapacityWarning::class, function (SpaceCapacityWarning $e) { // $e->space و$e->usedBytes و$e->capacityBytes و$e->percent }); ``` -الحدث يطلق مرة واحدة عند *تجاوز* الاستخدام النسبة المضبوطة (`MAKHZAN_CAPACITY_WARNING_PERCENT`، افتراضياً 80)، وليس مع كل كتابة فوق الخط. +الحدث يطلق مرة واحدة عند *تجاوز* الاستخدام النسبة المضبوطة (`STORELY_CAPACITY_WARNING_PERCENT`، افتراضياً 80)، وليس مع كل كتابة فوق الخط. ### النسخ الاحتياطي (Mirror) اربط مساحة نسخ، وكل كتابة جديدة تُنسخ إليها عبر Job في الطابور: ```php -Makhzan::spaces()->setMirror($main, $backup); +Storely::spaces()->setMirror($main, $backup); ``` ### تفريغ مساحة @@ -199,7 +201,7 @@ Makhzan::spaces()->setMirror($main, $backup); لسحب مساحة من الخدمة، فرّغها في أخرى بالخلفية: ```php -$move = Makhzan::drain($from, $to); // سجل MakhzanMove فيه total/done/failed +$move = Storely::drain($from, $to); // سجل StorelyMove فيه total/done/failed ``` المصدر يصبح `draining` (القراءة تستمر والكتابة تتوقف)، وكل نسخة تُنقل فقط بعد التحقق من الجديدة ببصمة SHA-256، وعند انتهاء التفريغ بنجاح تُحال المساحة إلى `disabled`. ويطلق حدث `MoveCompleted` في النهاية. @@ -225,18 +227,18 @@ $move = Makhzan::drain($from, $to); // سجل MakhzanMove فيه total/done/fa - البيانات السرية تُحفظ بتحويل `encrypted:array` في Laravel وتُستبعد من التسلسل (`$hidden`)؛ القيمة الخام في قاعدة البيانات مشفرة. - لا تخدم المساحة الملفات إلا ما دامت بياناتها المخزنة مطابقة للبيانات التي نجحت في الفحص الحي. -- الروابط يجب أن تكون `https://` بأسماء نطاقات (بدون IP)؛ وجذر القرص المحلي مقيد باسم مجلد آمن تحت `storage/app/makhzan`. +- الروابط يجب أن تكون `https://` بأسماء نطاقات (بدون IP)؛ وجذر القرص المحلي مقيد باسم مجلد آمن تحت `storage/app/storely`. - أسماء الملفات المخزنة تُختزل إلى Basename آمن. -- مخزن **لا يطبق صلاحيات**: أي كود يستدعي `Makhzan::spaces()` يستطيع إدارة المساحات. احمِ هذه الاستدعاءات في لوحة الإدارة الخاصة بك (Policy أو Middleware أو صلاحية) كما تحمي أي إجراء إداري آخر. +- ستورلي **لا يطبق صلاحيات**: أي كود يستدعي `Storely::spaces()` يستطيع إدارة المساحات. احمِ هذه الاستدعاءات في لوحة الإدارة الخاصة بك (Policy أو Middleware أو صلاحية) كما تحمي أي إجراء إداري آخر. ## الإعدادات | المفتاح | متغير البيئة | الافتراضي | الوظيفة | | --- | --- | --- | --- | -| `max_upload_bytes` | `MAKHZAN_MAX_UPLOAD_BYTES` | 512 ميجابايت | الحد الأقصى لحجم الملف | -| `capacity_warning_percent` | `MAKHZAN_CAPACITY_WARNING_PERCENT` | 80 | خط التنبيه | -| `queue` | `MAKHZAN_QUEUE` | الافتراضي | طابور مهام النسخ والتفريغ | -| `local_root` | `MAKHZAN_LOCAL_ROOT` | `app/makhzan` | مكان مساحات `local` تحت `storage_path()` | +| `max_upload_bytes` | `STORELY_MAX_UPLOAD_BYTES` | 512 ميجابايت | الحد الأقصى لحجم الملف | +| `capacity_warning_percent` | `STORELY_CAPACITY_WARNING_PERCENT` | 80 | خط التنبيه | +| `queue` | `STORELY_QUEUE` | الافتراضي | طابور مهام النسخ والتفريغ | +| `local_root` | `STORELY_LOCAL_ROOT` | `app/storely` | مكان مساحات `local` تحت `storage_path()` | ## الاختبارات diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 9337033..968735f 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -5,7 +5,7 @@ colors="true" cacheDirectory=".phpunit.cache"> - + tests diff --git a/src/Console/GcCommand.php b/src/Console/GcCommand.php index eaaca64..455b545 100644 --- a/src/Console/GcCommand.php +++ b/src/Console/GcCommand.php @@ -2,15 +2,15 @@ declare(strict_types=1); -namespace Makhzan\Console; +namespace Storely\Console; use Illuminate\Console\Command; -use Makhzan\Services\GcService; +use Storely\Services\GcService; class GcCommand extends Command { /** @var string */ - protected $signature = 'makhzan:gc {--check-remote : Ask every space whether each copy still exists} {--purge : Also delete file records left with no copies} {--dry-run : Report only, remove nothing}'; + protected $signature = 'storely:gc {--check-remote : Ask every space whether each copy still exists} {--purge : Also delete file records left with no copies} {--dry-run : Report only, remove nothing}'; /** @var string */ protected $description = 'Remove database rows pointing at storage that no longer exists.'; diff --git a/src/Console/HealthCheckCommand.php b/src/Console/HealthCheckCommand.php index f3eefb5..a4f6b57 100644 --- a/src/Console/HealthCheckCommand.php +++ b/src/Console/HealthCheckCommand.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace Makhzan\Console; +namespace Storely\Console; use Illuminate\Console\Command; -use Makhzan\Models\MakhzanSpace; -use Makhzan\Services\HealthService; +use Storely\Models\StorelySpace; +use Storely\Services\HealthService; class HealthCheckCommand extends Command { /** @var string */ - protected $signature = 'makhzan:health {--space= : Check one space by id or name}'; + protected $signature = 'storely:health {--space= : Check one space by id or name}'; /** @var string */ protected $description = 'Run the live health check on every storage space (or one).'; @@ -21,8 +21,8 @@ public function handle(HealthService $health): int $selector = $this->option('space'); if (is_string($selector) && $selector !== '') { $space = is_numeric($selector) - ? MakhzanSpace::find((int) $selector) - : MakhzanSpace::where('name', $selector)->first(); + ? StorelySpace::find((int) $selector) + : StorelySpace::where('name', $selector)->first(); if ($space === null) { $this->error('Space not found: '.$selector); diff --git a/src/Console/PruneCommand.php b/src/Console/PruneCommand.php index 639b9d8..c7b6f98 100644 --- a/src/Console/PruneCommand.php +++ b/src/Console/PruneCommand.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace Makhzan\Console; +namespace Storely\Console; use Illuminate\Console\Command; -use Makhzan\Models\MakhzanFile; -use Makhzan\Services\FileStoreService; +use Storely\Models\StorelyFile; +use Storely\Services\FileStoreService; class PruneCommand extends Command { /** @var string */ - protected $signature = 'makhzan:prune {--days=30 : Soft-deleted files older than this many days go} {--dry-run : List what would be pruned without deleting}'; + protected $signature = 'storely:prune {--days=30 : Soft-deleted files older than this many days go} {--dry-run : List what would be pruned without deleting}'; /** @var string */ protected $description = 'Permanently delete old soft-deleted files and their remote copies.'; @@ -22,10 +22,10 @@ public function handle(FileStoreService $files): int $dry = (bool) $this->option('dry-run'); $cutoff = now()->subDays($days); - $query = MakhzanFile::onlyTrashed()->where('deleted_at', '<=', $cutoff)->orderBy('id'); + $query = StorelyFile::onlyTrashed()->where('deleted_at', '<=', $cutoff)->orderBy('id'); $count = 0; foreach ($query->cursor() as $file) { - /** @var MakhzanFile $file */ + /** @var StorelyFile $file */ $count++; if ($dry) { $this->line("would prune: #{$file->id} {$file->original_name} ({$file->size} bytes, deleted {$file->deleted_at})"); diff --git a/src/Console/ReplicateCommand.php b/src/Console/ReplicateCommand.php index 9408f95..ddb3e0b 100644 --- a/src/Console/ReplicateCommand.php +++ b/src/Console/ReplicateCommand.php @@ -2,27 +2,27 @@ declare(strict_types=1); -namespace Makhzan\Console; +namespace Storely\Console; use Illuminate\Console\Command; -use Makhzan\Models\MakhzanFile; -use Makhzan\Models\MakhzanFileLocation; -use Makhzan\Models\MakhzanSpace; -use Makhzan\Services\FileStoreService; +use Storely\Models\StorelyFile; +use Storely\Models\StorelyFileLocation; +use Storely\Models\StorelySpace; +use Storely\Services\FileStoreService; use Throwable; class ReplicateCommand extends Command { /** @var string */ - protected $signature = 'makhzan:replicate {from : Source space id} {to : Target space id}'; + protected $signature = 'storely:replicate {from : Source space id} {to : Target space id}'; /** @var string */ protected $description = 'Copy every file on one space to another space (verified, source untouched).'; public function handle(FileStoreService $files): int { - $from = MakhzanSpace::find((int) $this->argument('from')); - $to = MakhzanSpace::find((int) $this->argument('to')); + $from = StorelySpace::find((int) $this->argument('from')); + $to = StorelySpace::find((int) $this->argument('to')); if ($from === null || $to === null) { $this->error('Both spaces must exist.'); @@ -34,16 +34,16 @@ public function handle(FileStoreService $files): int return self::FAILURE; } - $fileIds = MakhzanFileLocation::query()->where('makhzan_space_id', $from->id)->distinct()->pluck('makhzan_file_id'); + $fileIds = StorelyFileLocation::query()->where('storely_space_id', $from->id)->distinct()->pluck('storely_file_id'); $copied = $skipped = $failed = 0; $this->withProgressBar($fileIds, function (int $fileId) use ($files, $to, &$copied, &$skipped, &$failed): void { - $file = MakhzanFile::find($fileId); + $file = StorelyFile::find($fileId); if ($file === null) { $skipped++; return; } - $already = MakhzanFileLocation::query()->where('makhzan_file_id', $file->id)->where('makhzan_space_id', $to->id)->exists(); + $already = StorelyFileLocation::query()->where('storely_file_id', $file->id)->where('storely_space_id', $to->id)->exists(); if ($already) { $skipped++; diff --git a/src/Console/UsageCommand.php b/src/Console/UsageCommand.php index 306e113..766ba38 100644 --- a/src/Console/UsageCommand.php +++ b/src/Console/UsageCommand.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace Makhzan\Console; +namespace Storely\Console; use Illuminate\Console\Command; -use Makhzan\Models\MakhzanSpace; -use Makhzan\Services\SpaceService; +use Storely\Models\StorelySpace; +use Storely\Services\SpaceService; class UsageCommand extends Command { /** @var string */ - protected $signature = 'makhzan:usage'; + protected $signature = 'storely:usage'; /** @var string */ protected $description = 'Show usage per storage space (files, bytes, percent of capacity).'; @@ -19,7 +19,7 @@ class UsageCommand extends Command public function handle(SpaceService $spaces): int { $rows = []; - foreach (MakhzanSpace::query()->orderBy('priority')->orderBy('id')->get() as $space) { + foreach (StorelySpace::query()->orderBy('priority')->orderBy('id')->get() as $space) { $u = $spaces->usage($space); $rows[] = [ $space->id, diff --git a/src/Console/VerifyCommand.php b/src/Console/VerifyCommand.php index 79bcfe5..16c4908 100644 --- a/src/Console/VerifyCommand.php +++ b/src/Console/VerifyCommand.php @@ -2,43 +2,43 @@ declare(strict_types=1); -namespace Makhzan\Console; +namespace Storely\Console; use Illuminate\Console\Command; -use Makhzan\DriverFactory; -use Makhzan\Exceptions\MakhzanException; -use Makhzan\Models\MakhzanFileLocation; -use Makhzan\Models\MakhzanSpace; +use Storely\DriverFactory; +use Storely\Exceptions\StorelyException; +use Storely\Models\StorelyFileLocation; +use Storely\Models\StorelySpace; class VerifyCommand extends Command { /** @var string */ - protected $signature = 'makhzan:verify {--space= : Verify copies on one space by id or name}'; + protected $signature = 'storely:verify {--space= : Verify copies on one space by id or name}'; /** @var string */ protected $description = 'Check that every recorded file copy still exists on its space.'; public function handle(DriverFactory $drivers): int { - $query = MakhzanFileLocation::query()->with(['space'])->orderBy('id'); + $query = StorelyFileLocation::query()->with(['space'])->orderBy('id'); $selector = $this->option('space'); if (is_string($selector) && $selector !== '') { $space = is_numeric($selector) - ? MakhzanSpace::find((int) $selector) - : MakhzanSpace::where('name', $selector)->first(); + ? StorelySpace::find((int) $selector) + : StorelySpace::where('name', $selector)->first(); if ($space === null) { $this->error('Space not found: '.$selector); return self::FAILURE; } - $query->where('makhzan_space_id', $space->id); + $query->where('storely_space_id', $space->id); } $checked = 0; $missing = 0; $unreachable = 0; foreach ($query->cursor() as $location) { - /** @var MakhzanFileLocation $location */ + /** @var StorelyFileLocation $location */ $space = $location->space; if ($space === null) { continue; @@ -49,9 +49,9 @@ public function handle(DriverFactory $drivers): int $location->forceFill(['verified_at' => now()])->save(); } else { $missing++; - $this->warn("missing: file {$location->makhzan_file_id} on space {$space->name} ({$space->id})"); + $this->warn("missing: file {$location->storely_file_id} on space {$space->name} ({$space->id})"); } - } catch (MakhzanException $e) { + } catch (StorelyException $e) { $unreachable++; $this->warn("unreachable: space {$space->name} ({$space->id}): {$e->getMessage()}"); } diff --git a/src/Contracts/StorageDriver.php b/src/Contracts/StorageDriver.php index 8ed04cd..19e12b2 100644 --- a/src/Contracts/StorageDriver.php +++ b/src/Contracts/StorageDriver.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Makhzan\Contracts; +namespace Storely\Contracts; interface StorageDriver { @@ -24,6 +24,6 @@ public function delete(string $locator): void; public function exists(string $locator): bool; - /** Live round trip (write, read back, delete). Returns a short human message or throws MakhzanException. */ + /** Live round trip (write, read back, delete). Returns a short human message or throws StorelyException. */ public function test(): string; } diff --git a/src/Contracts/SupportsTemporaryUrls.php b/src/Contracts/SupportsTemporaryUrls.php index 81f1dc3..789ea18 100644 --- a/src/Contracts/SupportsTemporaryUrls.php +++ b/src/Contracts/SupportsTemporaryUrls.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Makhzan\Contracts; +namespace Storely\Contracts; use DateTimeInterface; @@ -10,7 +10,7 @@ interface SupportsTemporaryUrls { /** - * A URL valid until $expiresAt. Throws MakhzanException when the space + * A URL valid until $expiresAt. Throws StorelyException when the space * cannot produce one (unsupported disk, unreachable provider). */ public function temporaryUrl(string $locator, DateTimeInterface $expiresAt): string; diff --git a/src/DriverFactory.php b/src/DriverFactory.php index dcec9e9..46e968a 100644 --- a/src/DriverFactory.php +++ b/src/DriverFactory.php @@ -2,29 +2,29 @@ declare(strict_types=1); -namespace Makhzan; +namespace Storely; use Illuminate\Contracts\Filesystem\Filesystem; use Illuminate\Support\Facades\Storage; use League\Flysystem\AwsS3V3\AwsS3V3Adapter; -use Makhzan\Contracts\StorageDriver; -use Makhzan\Drivers\FlysystemDriver; -use Makhzan\Drivers\GoogleDriveDriver; -use Makhzan\Drivers\TelegramDriver; -use Makhzan\Enums\SpaceDriver; -use Makhzan\Exceptions\MakhzanException; -use Makhzan\Models\MakhzanSpace; +use Storely\Contracts\StorageDriver; +use Storely\Drivers\FlysystemDriver; +use Storely\Drivers\GoogleDriveDriver; +use Storely\Drivers\TelegramDriver; +use Storely\Enums\SpaceDriver; +use Storely\Exceptions\StorelyException; +use Storely\Models\StorelySpace; class DriverFactory { - public function make(MakhzanSpace $space): StorageDriver + public function make(StorelySpace $space): StorageDriver { $c = $space->credentials; return match ($space->driver) { SpaceDriver::Local => new FlysystemDriver(Storage::build([ 'driver' => 'local', - 'root' => storage_path(trim((string) config('makhzan.local_root', 'app/makhzan'), '/').'/'.$c['root']), + 'root' => storage_path(trim((string) config('storely.local_root', 'app/storely'), '/').'/'.$c['root']), 'throw' => true, ])), SpaceDriver::R2 => new FlysystemDriver($this->s3( @@ -44,7 +44,7 @@ public function make(MakhzanSpace $space): StorageDriver private function s3(string $endpoint, string $region, array $c): Filesystem { if (! class_exists(AwsS3V3Adapter::class)) { - throw new MakhzanException( + throw new StorelyException( 'S3-compatible spaces need the Flysystem AWS adapter: composer require league/flysystem-aws-s3-v3' ); } diff --git a/src/Drivers/FlysystemDriver.php b/src/Drivers/FlysystemDriver.php index 403473a..f3f3678 100644 --- a/src/Drivers/FlysystemDriver.php +++ b/src/Drivers/FlysystemDriver.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace Makhzan\Drivers; +namespace Storely\Drivers; use DateTimeInterface; use Illuminate\Contracts\Filesystem\Filesystem; -use Makhzan\Contracts\StorageDriver; -use Makhzan\Contracts\SupportsTemporaryUrls; -use Makhzan\Exceptions\MakhzanException; +use Storely\Contracts\StorageDriver; +use Storely\Contracts\SupportsTemporaryUrls; +use Storely\Exceptions\StorelyException; use Throwable; /** Shared by local-disk spaces and the S3-compatible providers (R2, B2, S3). Locator = object key. */ @@ -21,10 +21,10 @@ public function put(string $key, $stream, ?string $mime = null): string try { $ok = $this->disk->writeStream($key, $stream, $mime ? ['mimetype' => $mime] : []); } catch (Throwable $e) { - throw new MakhzanException('Uploading the file to the space failed.', 0, $e); + throw new StorelyException('Uploading the file to the space failed.', 0, $e); } if ($ok === false) { - throw new MakhzanException('Uploading the file to the space failed.'); + throw new StorelyException('Uploading the file to the space failed.'); } return $key; @@ -35,10 +35,10 @@ public function read(string $locator) try { $stream = $this->disk->readStream($locator); } catch (Throwable $e) { - throw new MakhzanException('Reading the file from the space failed.', 0, $e); + throw new StorelyException('Reading the file from the space failed.', 0, $e); } if (! is_resource($stream)) { - throw new MakhzanException('The file does not exist on the space.'); + throw new StorelyException('The file does not exist on the space.'); } return $stream; @@ -49,7 +49,7 @@ public function delete(string $locator): void try { $this->disk->delete($locator); } catch (Throwable $e) { - throw new MakhzanException('Deleting the file from the space failed.', 0, $e); + throw new StorelyException('Deleting the file from the space failed.', 0, $e); } } @@ -58,7 +58,7 @@ public function exists(string $locator): bool try { return $this->disk->exists($locator); } catch (Throwable $e) { - throw new MakhzanException('Reaching the space failed.', 0, $e); + throw new StorelyException('Reaching the space failed.', 0, $e); } } @@ -67,17 +67,17 @@ public function temporaryUrl(string $locator, DateTimeInterface $expiresAt): str try { return $this->disk->temporaryUrl($locator, $expiresAt); } catch (Throwable $e) { - throw new MakhzanException('This space cannot create temporary URLs.', 0, $e); + throw new StorelyException('This space cannot create temporary URLs.', 0, $e); } } public function test(): string { - $key = '.makhzan-check/'.bin2hex(random_bytes(8)).'.txt'; - $payload = 'makhzan-'.bin2hex(random_bytes(8)); + $key = '.storely-check/'.bin2hex(random_bytes(8)).'.txt'; + $payload = 'storely-'.bin2hex(random_bytes(8)); $stream = fopen('php://temp', 'r+'); if ($stream === false) { - throw new MakhzanException('Could not open a temporary stream.'); + throw new StorelyException('Could not open a temporary stream.'); } fwrite($stream, $payload); rewind($stream); @@ -86,7 +86,7 @@ public function test(): string try { $back = stream_get_contents($this->read($locator)); if ($back !== $payload) { - throw new MakhzanException('The read-back content does not match the uploaded content.'); + throw new StorelyException('The read-back content does not match the uploaded content.'); } } finally { $this->delete($locator); diff --git a/src/Drivers/GoogleDriveDriver.php b/src/Drivers/GoogleDriveDriver.php index 5a19ce9..6aa7029 100644 --- a/src/Drivers/GoogleDriveDriver.php +++ b/src/Drivers/GoogleDriveDriver.php @@ -2,13 +2,13 @@ declare(strict_types=1); -namespace Makhzan\Drivers; +namespace Storely\Drivers; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Client\Response; use Illuminate\Support\Facades\Http; -use Makhzan\Contracts\StorageDriver; -use Makhzan\Exceptions\MakhzanException; +use Storely\Contracts\StorageDriver; +use Storely\Exceptions\StorelyException; use Throwable; /** Google Drive via an OAuth refresh token, files kept inside one dedicated folder. Locator = Drive file id. */ @@ -21,19 +21,19 @@ public function put(string $key, $stream, ?string $mime = null): string { $contents = stream_get_contents($stream); if ($contents === false) { - throw new MakhzanException('Could not read the source stream.'); + throw new StorelyException('Could not read the source stream.'); } $meta = json_encode(['name' => basename($key), 'parents' => [$this->credentials['folder_id']]], JSON_THROW_ON_ERROR); - $res = $this->request(fn (PendingRequest $http) => $http->withHeaders(['Content-Type' => 'multipart/related; boundary=makhzanb']) + $res = $this->request(fn (PendingRequest $http) => $http->withHeaders(['Content-Type' => 'multipart/related; boundary=storelyb']) ->withBody( - "--makhzanb\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{$meta}\r\n--makhzanb\r\nContent-Type: ".($mime ?: 'application/octet-stream')."\r\n\r\n" - .$contents."\r\n--makhzanb--", - 'multipart/related; boundary=makhzanb' + "--storelyb\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{$meta}\r\n--storelyb\r\nContent-Type: ".($mime ?: 'application/octet-stream')."\r\n\r\n" + .$contents."\r\n--storelyb--", + 'multipart/related; boundary=storelyb' )->post('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id')); $id = $res->json('id'); if (! is_string($id) || $id === '') { - throw new MakhzanException('Unexpected response from Google Drive.'); + throw new StorelyException('Unexpected response from Google Drive.'); } return $id; @@ -44,7 +44,7 @@ public function read(string $locator) $res = $this->request(fn (PendingRequest $http) => $http->get('https://www.googleapis.com/drive/v3/files/'.rawurlencode($locator).'?alt=media')); $out = fopen('php://temp', 'r+'); if ($out === false) { - throw new MakhzanException('Could not open a temporary stream.'); + throw new StorelyException('Could not open a temporary stream.'); } fwrite($out, $res->body()); rewind($out); @@ -63,7 +63,7 @@ public function exists(string $locator): bool $this->request(fn (PendingRequest $http) => $http->get('https://www.googleapis.com/drive/v3/files/'.rawurlencode($locator).'?fields=id,trashed')); return true; - } catch (MakhzanException) { + } catch (StorelyException) { return false; } } @@ -74,15 +74,15 @@ public function test(): string $stream = fopen('php://temp', 'r+'); if ($stream === false) { - throw new MakhzanException('Could not open a temporary stream.'); + throw new StorelyException('Could not open a temporary stream.'); } - fwrite($stream, 'makhzan-check'); + fwrite($stream, 'storely-check'); rewind($stream); - $id = $this->put('makhzan-check.txt', $stream, 'text/plain'); + $id = $this->put('storely-check.txt', $stream, 'text/plain'); try { $back = stream_get_contents($this->read($id)); - if ($back !== 'makhzan-check') { - throw new MakhzanException('The read-back content does not match the uploaded content.'); + if ($back !== 'storely-check') { + throw new StorelyException('The read-back content does not match the uploaded content.'); } } finally { $this->delete($id); @@ -101,11 +101,11 @@ private function token(): string 'grant_type' => 'refresh_token', ]); } catch (Throwable $e) { - throw new MakhzanException('Could not reach Google.', 0, $e); + throw new StorelyException('Could not reach Google.', 0, $e); } $token = $res->json('access_token'); if (! $res->successful() || ! is_string($token)) { - throw new MakhzanException('Google rejected the credentials (check the Client ID and Refresh Token).'); + throw new StorelyException('Google rejected the credentials (check the Client ID and Refresh Token).'); } return $token; @@ -118,10 +118,10 @@ private function request(callable $call): Response try { $res = $call($http); } catch (Throwable $e) { - throw new MakhzanException('Could not reach Google Drive.', 0, $e); + throw new StorelyException('Could not reach Google Drive.', 0, $e); } if (! $res->successful()) { - throw new MakhzanException('Google Drive rejected the request (status '.$res->status().').'); + throw new StorelyException('Google Drive rejected the request (status '.$res->status().').'); } return $res; diff --git a/src/Drivers/TelegramDriver.php b/src/Drivers/TelegramDriver.php index 456e58d..4d66689 100644 --- a/src/Drivers/TelegramDriver.php +++ b/src/Drivers/TelegramDriver.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace Makhzan\Drivers; +namespace Storely\Drivers; use Illuminate\Support\Facades\Http; -use Makhzan\Contracts\StorageDriver; -use Makhzan\Exceptions\MakhzanException; +use Storely\Contracts\StorageDriver; +use Storely\Exceptions\StorelyException; use Throwable; /** @@ -28,7 +28,7 @@ public function put(string $key, $stream, ?string $mime = null): string $messageId = $res['result']['message_id'] ?? null; $fileId = $res['result']['document']['file_id'] ?? null; if (! is_numeric($messageId) || ! is_string($fileId) || $fileId === '') { - throw new MakhzanException('Unexpected response from Telegram.'); + throw new StorelyException('Unexpected response from Telegram.'); } return $messageId.':'.$fileId; @@ -45,7 +45,7 @@ public function read(string $locator) $info = $this->call('getFile', ['file_id' => $fileId]); $path = $info['result']['file_path'] ?? null; if (! is_string($path) || $path === '') { - throw new MakhzanException('The file is not available on Telegram.'); + throw new StorelyException('The file is not available on Telegram.'); } $url = self::API.'/file/bot'.$this->credentials['bot_token'].'/'.$path; } @@ -53,14 +53,14 @@ public function read(string $locator) try { $res = Http::timeout(60)->get($url); } catch (Throwable $e) { - throw new MakhzanException('Downloading the file from Telegram failed.', 0, $e); + throw new StorelyException('Downloading the file from Telegram failed.', 0, $e); } if (! $res->successful()) { - throw new MakhzanException('Downloading the file from Telegram failed.'); + throw new StorelyException('Downloading the file from Telegram failed.'); } $out = fopen('php://temp', 'r+'); if ($out === false) { - throw new MakhzanException('Could not open a temporary stream.'); + throw new StorelyException('Could not open a temporary stream.'); } fwrite($out, $res->body()); rewind($out); @@ -80,7 +80,7 @@ public function exists(string $locator): bool try { $res = Http::timeout(20)->asForm()->post($this->url('getFile'), ['file_id' => $fileId]); } catch (Throwable $e) { - throw new MakhzanException('Could not reach Telegram.', 0, $e); + throw new StorelyException('Could not reach Telegram.', 0, $e); } return $res->successful() && ($res->json('ok') === true); @@ -93,11 +93,11 @@ public function test(): string $stream = fopen('php://temp', 'r+'); if ($stream === false) { - throw new MakhzanException('Could not open a temporary stream.'); + throw new StorelyException('Could not open a temporary stream.'); } - fwrite($stream, 'makhzan-check'); + fwrite($stream, 'storely-check'); rewind($stream); - $locator = $this->put('makhzan-check.txt', $stream); + $locator = $this->put('storely-check.txt', $stream); $this->delete($locator); return "Telegram check passed with @{$name}: sent and deleted a test document."; @@ -124,12 +124,12 @@ private function call(string $method, array $fields, ?array $file = null): array } $res = $req->post($this->url($method), $fields); } catch (Throwable $e) { - throw new MakhzanException('Could not reach Telegram.', 0, $e); + throw new StorelyException('Could not reach Telegram.', 0, $e); } if (! $res->successful() || $res->json('ok') !== true) { // The description never includes our token; Telegram echoes only its own error text. - throw new MakhzanException('Telegram rejected the request: '.(string) ($res->json('description') ?? $res->status())); + throw new StorelyException('Telegram rejected the request: '.(string) ($res->json('description') ?? $res->status())); } /** @var array */ @@ -141,7 +141,7 @@ private function split(string $locator): array { $parts = explode(':', $locator, 2); if (count($parts) !== 2 || $parts[0] === '' || $parts[1] === '' || ! ctype_digit($parts[0])) { - throw new MakhzanException('Invalid Telegram file locator.'); + throw new StorelyException('Invalid Telegram file locator.'); } return [$parts[0], $parts[1]]; diff --git a/src/Enums/LocationRole.php b/src/Enums/LocationRole.php index 3a447c0..a4580f0 100644 --- a/src/Enums/LocationRole.php +++ b/src/Enums/LocationRole.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Makhzan\Enums; +namespace Storely\Enums; enum LocationRole: string { diff --git a/src/Enums/MoveStatus.php b/src/Enums/MoveStatus.php index 297c0df..dd600a9 100644 --- a/src/Enums/MoveStatus.php +++ b/src/Enums/MoveStatus.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Makhzan\Enums; +namespace Storely\Enums; enum MoveStatus: string { diff --git a/src/Enums/SpaceDriver.php b/src/Enums/SpaceDriver.php index 301c25b..1ee4372 100644 --- a/src/Enums/SpaceDriver.php +++ b/src/Enums/SpaceDriver.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Makhzan\Enums; +namespace Storely\Enums; enum SpaceDriver: string { diff --git a/src/Enums/SpaceStatus.php b/src/Enums/SpaceStatus.php index 26b92c9..a2d0e3a 100644 --- a/src/Enums/SpaceStatus.php +++ b/src/Enums/SpaceStatus.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Makhzan\Enums; +namespace Storely\Enums; enum SpaceStatus: string { diff --git a/src/Events/FileStored.php b/src/Events/FileStored.php index 5a014c8..5675bdf 100644 --- a/src/Events/FileStored.php +++ b/src/Events/FileStored.php @@ -2,19 +2,19 @@ declare(strict_types=1); -namespace Makhzan\Events; +namespace Storely\Events; use Illuminate\Foundation\Events\Dispatchable; -use Makhzan\Models\MakhzanFile; -use Makhzan\Models\MakhzanFileLocation; +use Storely\Models\StorelyFile; +use Storely\Models\StorelyFileLocation; class FileStored { use Dispatchable; public function __construct( - public readonly MakhzanFile $file, - public readonly MakhzanFileLocation $location, + public readonly StorelyFile $file, + public readonly StorelyFileLocation $location, public readonly bool $deduplicated, ) {} } diff --git a/src/Events/MoveCompleted.php b/src/Events/MoveCompleted.php index 1a78132..4b07379 100644 --- a/src/Events/MoveCompleted.php +++ b/src/Events/MoveCompleted.php @@ -2,15 +2,15 @@ declare(strict_types=1); -namespace Makhzan\Events; +namespace Storely\Events; use Illuminate\Foundation\Events\Dispatchable; -use Makhzan\Models\MakhzanMove; +use Storely\Models\StorelyMove; /** Fired when a background drain between two spaces finishes (with or without failures). */ class MoveCompleted { use Dispatchable; - public function __construct(public readonly MakhzanMove $move) {} + public function __construct(public readonly StorelyMove $move) {} } diff --git a/src/Events/SpaceCapacityWarning.php b/src/Events/SpaceCapacityWarning.php index 642f315..3a9bde0 100644 --- a/src/Events/SpaceCapacityWarning.php +++ b/src/Events/SpaceCapacityWarning.php @@ -2,10 +2,10 @@ declare(strict_types=1); -namespace Makhzan\Events; +namespace Storely\Events; use Illuminate\Foundation\Events\Dispatchable; -use Makhzan\Models\MakhzanSpace; +use Storely\Models\StorelySpace; /** * Fired once when a space's used bytes cross the configured warning percent of its @@ -16,7 +16,7 @@ class SpaceCapacityWarning use Dispatchable; public function __construct( - public readonly MakhzanSpace $space, + public readonly StorelySpace $space, public readonly int $usedBytes, public readonly int $capacityBytes, public readonly int $percent, diff --git a/src/Events/SpaceChecked.php b/src/Events/SpaceChecked.php index 51a1dc9..fa965f3 100644 --- a/src/Events/SpaceChecked.php +++ b/src/Events/SpaceChecked.php @@ -2,10 +2,10 @@ declare(strict_types=1); -namespace Makhzan\Events; +namespace Storely\Events; use Illuminate\Foundation\Events\Dispatchable; -use Makhzan\Models\MakhzanSpace; +use Storely\Models\StorelySpace; /** Fired after every live health check, passing or failing. */ class SpaceChecked @@ -13,7 +13,7 @@ class SpaceChecked use Dispatchable; public function __construct( - public readonly MakhzanSpace $space, + public readonly StorelySpace $space, public readonly bool $ok, public readonly string $message, ) {} diff --git a/src/Events/SpaceFailover.php b/src/Events/SpaceFailover.php index b781f4f..450972d 100644 --- a/src/Events/SpaceFailover.php +++ b/src/Events/SpaceFailover.php @@ -2,19 +2,19 @@ declare(strict_types=1); -namespace Makhzan\Events; +namespace Storely\Events; use Illuminate\Foundation\Events\Dispatchable; -use Makhzan\Models\MakhzanSpace; +use Storely\Models\StorelySpace; -/** Fired when a write fails on one space and Makhzan moves on to the next candidate. */ +/** Fired when a write fails on one space and Storely moves on to the next candidate. */ class SpaceFailover { use Dispatchable; public function __construct( - public readonly MakhzanSpace $from, - public readonly MakhzanSpace $to, + public readonly StorelySpace $from, + public readonly StorelySpace $to, public readonly string $reason, ) {} } diff --git a/src/Exceptions/AllSpacesFailedException.php b/src/Exceptions/AllSpacesFailedException.php index f3f5dcb..0862177 100644 --- a/src/Exceptions/AllSpacesFailedException.php +++ b/src/Exceptions/AllSpacesFailedException.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace Makhzan\Exceptions; +namespace Storely\Exceptions; /** * Every candidate space rejected the write. Carries the per-space failures. */ -class AllSpacesFailedException extends MakhzanException +class AllSpacesFailedException extends StorelyException { /** @param array $failures space id => failure message */ public function __construct(public readonly array $failures) diff --git a/src/Exceptions/MakhzanException.php b/src/Exceptions/MakhzanException.php deleted file mode 100644 index 90bb85e..0000000 --- a/src/Exceptions/MakhzanException.php +++ /dev/null @@ -1,9 +0,0 @@ - $credentials, int $priority = 100, ?int $capacityBytes = null) - * @method static array usage() - * @method static \Makhzan\Models\MakhzanMove drain(\Makhzan\Models\MakhzanSpace $from, \Makhzan\Models\MakhzanSpace $to, ?int $startedBy = null) - * - * @see \Makhzan\Makhzan - */ -class Makhzan extends Facade -{ - protected static function getFacadeAccessor(): string - { - return \Makhzan\Makhzan::class; - } -} diff --git a/src/Facades/Storely.php b/src/Facades/Storely.php new file mode 100644 index 0000000..1af98f0 --- /dev/null +++ b/src/Facades/Storely.php @@ -0,0 +1,34 @@ + $credentials, int $priority = 100, ?int $capacityBytes = null) + * @method static array usage() + * @method static \Storely\Models\StorelyMove drain(\Storely\Models\StorelySpace $from, \Storely\Models\StorelySpace $to, ?int $startedBy = null) + * + * @see \Storely\Storely + */ +class Storely extends Facade +{ + protected static function getFacadeAccessor(): string + { + return \Storely\Storely::class; + } +} diff --git a/src/Jobs/MirrorFileJob.php b/src/Jobs/MirrorFileJob.php index 318ea05..0d63091 100644 --- a/src/Jobs/MirrorFileJob.php +++ b/src/Jobs/MirrorFileJob.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace Makhzan\Jobs; +namespace Storely\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; -use Makhzan\Enums\LocationRole; -use Makhzan\Models\MakhzanFile; -use Makhzan\Models\MakhzanSpace; -use Makhzan\Services\FileStoreService; +use Storely\Enums\LocationRole; +use Storely\Models\StorelyFile; +use Storely\Models\StorelySpace; +use Storely\Services\FileStoreService; class MirrorFileJob implements ShouldQueue { @@ -23,7 +23,7 @@ public function __construct( public readonly int $fileId, public readonly int $spaceId, ) { - $queue = config('makhzan.queue'); + $queue = config('storely.queue'); if (is_string($queue) && $queue !== '') { $this->onQueue($queue); } @@ -31,8 +31,8 @@ public function __construct( public function handle(FileStoreService $files): void { - $file = MakhzanFile::find($this->fileId); - $space = MakhzanSpace::find($this->spaceId); + $file = StorelyFile::find($this->fileId); + $space = StorelySpace::find($this->spaceId); if ($file === null || $space === null) { return; // the file or the space was deleted while the job waited } diff --git a/src/Jobs/MoveLocationJob.php b/src/Jobs/MoveLocationJob.php index c5a47f0..92f77f5 100644 --- a/src/Jobs/MoveLocationJob.php +++ b/src/Jobs/MoveLocationJob.php @@ -2,20 +2,20 @@ declare(strict_types=1); -namespace Makhzan\Jobs; +namespace Storely\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Support\Facades\DB; -use Makhzan\Enums\MoveStatus; -use Makhzan\Enums\SpaceStatus; -use Makhzan\Events\MoveCompleted; -use Makhzan\Models\MakhzanFileLocation; -use Makhzan\Models\MakhzanMove; -use Makhzan\Models\MakhzanSpace; -use Makhzan\Services\FileStoreService; +use Storely\Enums\MoveStatus; +use Storely\Enums\SpaceStatus; +use Storely\Events\MoveCompleted; +use Storely\Models\StorelyFileLocation; +use Storely\Models\StorelyMove; +use Storely\Models\StorelySpace; +use Storely\Services\FileStoreService; use Throwable; class MoveLocationJob implements ShouldQueue @@ -28,7 +28,7 @@ public function __construct( public readonly int $moveId, public readonly int $locationId, ) { - $queue = config('makhzan.queue'); + $queue = config('storely.queue'); if (is_string($queue) && $queue !== '') { $this->onQueue($queue); } @@ -36,15 +36,15 @@ public function __construct( public function handle(FileStoreService $files): void { - $move = MakhzanMove::find($this->moveId); - $location = MakhzanFileLocation::find($this->locationId); + $move = StorelyMove::find($this->moveId); + $location = StorelyFileLocation::find($this->locationId); if ($move === null || $location === null) { $this->tally($move, false); return; } - /** @var MakhzanSpace|null $target */ - $target = MakhzanSpace::find($move->to_space_id); + /** @var StorelySpace|null $target */ + $target = StorelySpace::find($move->to_space_id); if ($target === null) { $this->tally($move, false); @@ -60,15 +60,15 @@ public function handle(FileStoreService $files): void } } - private function tally(?MakhzanMove $move, bool $ok): void + private function tally(?StorelyMove $move, bool $ok): void { if ($move === null) { return; } DB::transaction(function () use ($move, $ok): void { - /** @var MakhzanMove $fresh */ - $fresh = MakhzanMove::lockForUpdate()->findOrFail($move->id); + /** @var StorelyMove $fresh */ + $fresh = StorelyMove::lockForUpdate()->findOrFail($move->id); if ($fresh->status !== MoveStatus::Running) { return; } @@ -81,7 +81,7 @@ private function tally(?MakhzanMove $move, bool $ok): void $fresh->status = $fresh->failed === 0 ? MoveStatus::Completed : MoveStatus::Failed; if ($fresh->failed === 0) { // The drained space hosts nothing anymore: park it. - MakhzanSpace::whereKey($fresh->from_space_id) + StorelySpace::whereKey($fresh->from_space_id) ->where('status', SpaceStatus::Draining->value) ->update(['status' => SpaceStatus::Disabled->value]); } diff --git a/src/Models/MakhzanFile.php b/src/Models/StorelyFile.php similarity index 77% rename from src/Models/MakhzanFile.php rename to src/Models/StorelyFile.php index c699565..56ebb4a 100644 --- a/src/Models/MakhzanFile.php +++ b/src/Models/StorelyFile.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Makhzan\Models; +namespace Storely\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; @@ -20,11 +20,11 @@ * @property string|null $mime * @property Carbon|null $deleted_at */ -class MakhzanFile extends Model +class StorelyFile extends Model { use SoftDeletes; - protected $table = 'makhzan_files'; + protected $table = 'storely_files'; protected $fillable = ['original_name', 'mime']; @@ -34,9 +34,9 @@ protected function casts(): array return ['size' => 'integer']; } - /** @return HasMany */ + /** @return HasMany */ public function locations(): HasMany { - return $this->hasMany(MakhzanFileLocation::class, 'makhzan_file_id'); + return $this->hasMany(StorelyFileLocation::class, 'storely_file_id'); } } diff --git a/src/Models/MakhzanFileLocation.php b/src/Models/StorelyFileLocation.php similarity index 64% rename from src/Models/MakhzanFileLocation.php rename to src/Models/StorelyFileLocation.php index de83dcf..f39ef24 100644 --- a/src/Models/MakhzanFileLocation.php +++ b/src/Models/StorelyFileLocation.php @@ -2,29 +2,29 @@ declare(strict_types=1); -namespace Makhzan\Models; +namespace Storely\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Carbon; -use Makhzan\Enums\LocationRole; +use Storely\Enums\LocationRole; /** * One copy of a file on one space. * * @property int $id - * @property int $makhzan_file_id - * @property int $makhzan_space_id + * @property int $storely_file_id + * @property int $storely_space_id * @property string $locator * @property LocationRole $role * @property Carbon|null $verified_at */ -class MakhzanFileLocation extends Model +class StorelyFileLocation extends Model { use SoftDeletes; - protected $table = 'makhzan_file_locations'; + protected $table = 'storely_file_locations'; /** @var array */ protected $attributes = ['role' => 'primary']; @@ -38,15 +38,15 @@ protected function casts(): array ]; } - /** @return BelongsTo */ + /** @return BelongsTo */ public function file(): BelongsTo { - return $this->belongsTo(MakhzanFile::class, 'makhzan_file_id'); + return $this->belongsTo(StorelyFile::class, 'storely_file_id'); } - /** @return BelongsTo */ + /** @return BelongsTo */ public function space(): BelongsTo { - return $this->belongsTo(MakhzanSpace::class, 'makhzan_space_id'); + return $this->belongsTo(StorelySpace::class, 'storely_space_id'); } } diff --git a/src/Models/MakhzanMove.php b/src/Models/StorelyMove.php similarity index 74% rename from src/Models/MakhzanMove.php rename to src/Models/StorelyMove.php index 76063b8..8ea9123 100644 --- a/src/Models/MakhzanMove.php +++ b/src/Models/StorelyMove.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace Makhzan\Models; +namespace Storely\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\SoftDeletes; -use Makhzan\Enums\MoveStatus; +use Storely\Enums\MoveStatus; /** * Progress record of a background drain between two spaces. @@ -21,11 +21,11 @@ * @property MoveStatus $status * @property int|null $started_by */ -class MakhzanMove extends Model +class StorelyMove extends Model { use SoftDeletes; - protected $table = 'makhzan_moves'; + protected $table = 'storely_moves'; /** @var array */ protected $attributes = ['total' => 0, 'done' => 0, 'failed' => 0, 'status' => 'running']; @@ -36,16 +36,16 @@ protected function casts(): array return ['status' => MoveStatus::class]; } - /** @return BelongsTo */ + /** @return BelongsTo */ public function from(): BelongsTo { - return $this->belongsTo(MakhzanSpace::class, 'from_space_id'); + return $this->belongsTo(StorelySpace::class, 'from_space_id'); } - /** @return BelongsTo */ + /** @return BelongsTo */ public function to(): BelongsTo { - return $this->belongsTo(MakhzanSpace::class, 'to_space_id'); + return $this->belongsTo(StorelySpace::class, 'to_space_id'); } public function percent(): int diff --git a/src/Models/MakhzanRoutingRule.php b/src/Models/StorelyRoutingRule.php similarity index 80% rename from src/Models/MakhzanRoutingRule.php rename to src/Models/StorelyRoutingRule.php index 392535f..dae11dc 100644 --- a/src/Models/MakhzanRoutingRule.php +++ b/src/Models/StorelyRoutingRule.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Makhzan\Models; +namespace Storely\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; @@ -19,17 +19,17 @@ * @property string $category * @property int|null $min_size * @property int|null $max_size - * @property int $makhzan_space_id + * @property int $storely_space_id * @property int|null $mirror_space_id * @property bool $is_active */ -class MakhzanRoutingRule extends Model +class StorelyRoutingRule extends Model { use SoftDeletes; public const ANY = 'any'; - protected $table = 'makhzan_routing_rules'; + protected $table = 'storely_routing_rules'; /** @var array */ protected $attributes = ['priority' => 100, 'category' => 'any', 'is_active' => true]; @@ -44,16 +44,16 @@ protected function casts(): array ]; } - /** @return BelongsTo */ + /** @return BelongsTo */ public function space(): BelongsTo { - return $this->belongsTo(MakhzanSpace::class, 'makhzan_space_id'); + return $this->belongsTo(StorelySpace::class, 'storely_space_id'); } - /** @return BelongsTo */ + /** @return BelongsTo */ public function mirror(): BelongsTo { - return $this->belongsTo(MakhzanSpace::class, 'mirror_space_id'); + return $this->belongsTo(StorelySpace::class, 'mirror_space_id'); } public function matches(int $size, string $category): bool diff --git a/src/Models/MakhzanSpace.php b/src/Models/StorelySpace.php similarity index 87% rename from src/Models/MakhzanSpace.php rename to src/Models/StorelySpace.php index 75e9703..694cdb5 100644 --- a/src/Models/MakhzanSpace.php +++ b/src/Models/StorelySpace.php @@ -2,15 +2,15 @@ declare(strict_types=1); -namespace Makhzan\Models; +namespace Storely\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Carbon; -use Makhzan\Enums\SpaceDriver; -use Makhzan\Enums\SpaceStatus; +use Storely\Enums\SpaceDriver; +use Storely\Enums\SpaceStatus; /** * A named storage space (a bucket, a Drive folder, a Telegram channel, a local disk). @@ -28,11 +28,11 @@ * @property bool $last_check_ok * @property string|null $last_check_message */ -class MakhzanSpace extends Model +class StorelySpace extends Model { use SoftDeletes; - protected $table = 'makhzan_spaces'; + protected $table = 'storely_spaces'; /** @var array */ protected $attributes = ['status' => 'disabled', 'last_check_ok' => false, 'priority' => 100]; @@ -56,13 +56,13 @@ protected function casts(): array ]; } - /** @return HasMany */ + /** @return HasMany */ public function locations(): HasMany { - return $this->hasMany(MakhzanFileLocation::class, 'makhzan_space_id'); + return $this->hasMany(StorelyFileLocation::class, 'storely_space_id'); } - /** @return BelongsTo */ + /** @return BelongsTo */ public function mirror(): BelongsTo { return $this->belongsTo(self::class, 'mirror_space_id'); diff --git a/src/Services/DrainService.php b/src/Services/DrainService.php index 8fe6a62..d6db44a 100644 --- a/src/Services/DrainService.php +++ b/src/Services/DrainService.php @@ -2,22 +2,22 @@ declare(strict_types=1); -namespace Makhzan\Services; +namespace Storely\Services; use Illuminate\Support\Facades\DB; use Illuminate\Validation\ValidationException; -use Makhzan\Enums\MoveStatus; -use Makhzan\Enums\SpaceStatus; -use Makhzan\Events\MoveCompleted; -use Makhzan\Jobs\MoveLocationJob; -use Makhzan\Models\MakhzanFileLocation; -use Makhzan\Models\MakhzanMove; -use Makhzan\Models\MakhzanSpace; +use Storely\Enums\MoveStatus; +use Storely\Enums\SpaceStatus; +use Storely\Events\MoveCompleted; +use Storely\Jobs\MoveLocationJob; +use Storely\Models\StorelyFileLocation; +use Storely\Models\StorelyMove; +use Storely\Models\StorelySpace; /** Safely empties one space into another in the background, with a progress record. */ class DrainService { - public function start(MakhzanSpace $from, MakhzanSpace $to, ?int $startedBy = null): MakhzanMove + public function start(StorelySpace $from, StorelySpace $to, ?int $startedBy = null): StorelyMove { if ($from->id === $to->id) { throw ValidationException::withMessages(['to' => 'Choose a different target space.']); @@ -26,11 +26,11 @@ public function start(MakhzanSpace $from, MakhzanSpace $to, ?int $startedBy = nu throw ValidationException::withMessages(['to' => 'The target space must be active with a passing check.']); } - $move = DB::transaction(function () use ($from, $to, $startedBy): MakhzanMove { + $move = DB::transaction(function () use ($from, $to, $startedBy): StorelyMove { // Lock the source space row: the "already running" check and the move // creation must be atomic, or two concurrent drains can both start. - $locked = MakhzanSpace::lockForUpdate()->findOrFail($from->id); - $busy = MakhzanMove::query()->where('status', MoveStatus::Running->value) + $locked = StorelySpace::lockForUpdate()->findOrFail($from->id); + $busy = StorelyMove::query()->where('status', MoveStatus::Running->value) ->where(fn ($q) => $q->where('from_space_id', $locked->id)->orWhere('to_space_id', $locked->id)) ->lockForUpdate() ->exists(); @@ -41,11 +41,11 @@ public function start(MakhzanSpace $from, MakhzanSpace $to, ?int $startedBy = nu $locked->status = SpaceStatus::Draining; $locked->save(); - $move = new MakhzanMove; + $move = new StorelyMove; $move->from_space_id = $locked->id; $move->to_space_id = $to->id; $move->started_by = $startedBy; - $move->total = MakhzanFileLocation::query()->where('makhzan_space_id', $locked->id)->count(); + $move->total = StorelyFileLocation::query()->where('storely_space_id', $locked->id)->count(); if ($move->total === 0) { $move->status = MoveStatus::Completed; } @@ -54,7 +54,7 @@ public function start(MakhzanSpace $from, MakhzanSpace $to, ?int $startedBy = nu return $move; }); - MakhzanFileLocation::query()->where('makhzan_space_id', $from->id)->pluck('id') + StorelyFileLocation::query()->where('storely_space_id', $from->id)->pluck('id') ->each(fn (int $id) => MoveLocationJob::dispatch($move->id, $id)); if ($move->total === 0) { diff --git a/src/Services/FileStoreService.php b/src/Services/FileStoreService.php index 68734ed..b212479 100644 --- a/src/Services/FileStoreService.php +++ b/src/Services/FileStoreService.php @@ -2,24 +2,24 @@ declare(strict_types=1); -namespace Makhzan\Services; +namespace Storely\Services; use Illuminate\Support\Facades\DB; -use Makhzan\Contracts\StorageDriver; -use Makhzan\Contracts\SupportsTemporaryUrls; -use Makhzan\DriverFactory; -use Makhzan\Enums\LocationRole; -use Makhzan\Enums\SpaceStatus; -use Makhzan\Events\FileStored; -use Makhzan\Events\SpaceCapacityWarning; -use Makhzan\Events\SpaceFailover; -use Makhzan\Exceptions\AllSpacesFailedException; -use Makhzan\Exceptions\MakhzanException; -use Makhzan\Exceptions\NoUsableSpaceException; -use Makhzan\Jobs\MirrorFileJob; -use Makhzan\Models\MakhzanFile; -use Makhzan\Models\MakhzanFileLocation; -use Makhzan\Models\MakhzanSpace; +use Storely\Contracts\StorageDriver; +use Storely\Contracts\SupportsTemporaryUrls; +use Storely\DriverFactory; +use Storely\Enums\LocationRole; +use Storely\Enums\SpaceStatus; +use Storely\Events\FileStored; +use Storely\Events\SpaceCapacityWarning; +use Storely\Events\SpaceFailover; +use Storely\Exceptions\AllSpacesFailedException; +use Storely\Exceptions\NoUsableSpaceException; +use Storely\Exceptions\StorelyException; +use Storely\Jobs\MirrorFileJob; +use Storely\Models\StorelyFile; +use Storely\Models\StorelyFileLocation; +use Storely\Models\StorelySpace; use Throwable; /** @@ -45,7 +45,7 @@ public function __construct( * @throws NoUsableSpaceException when no space can accept the file * @throws AllSpacesFailedException when every candidate rejected the write */ - public function store($stream, string $name, ?string $mime = null, string $category = 'general'): MakhzanFile + public function store($stream, string $name, ?string $mime = null, string $category = 'general'): StorelyFile { [$path, $sha, $size] = $this->spool($stream); @@ -71,11 +71,11 @@ public function store($stream, string $name, ?string $mime = null, string $categ $key = $this->keyFor($sha); $handle = fopen($path, 'rb'); if ($handle === false) { - throw new MakhzanException('Could not re-open the spooled upload.'); + throw new StorelyException('Could not re-open the spooled upload.'); } try { $locator = $driver->put($key, $handle, $mime); - } catch (MakhzanException $e) { + } catch (StorelyException $e) { $failures[$space->id] = $e->getMessage(); $next = $candidates[$index + 1]['space'] ?? null; if ($next !== null) { @@ -108,40 +108,40 @@ public function store($stream, string $name, ?string $mime = null, string $categ /** * Opens the file, trying the primary location first and then the mirrors. * - * @return array{stream: resource, space: MakhzanSpace} + * @return array{stream: resource, space: StorelySpace} */ - public function read(MakhzanFile $file, ?int $excludeSpaceId = null): array + public function read(StorelyFile $file, ?int $excludeSpaceId = null): array { $locations = $file->locations()->with('space')->get() - ->filter(fn (MakhzanFileLocation $l) => $l->space !== null && $l->space->status !== SpaceStatus::Disabled && $l->makhzan_space_id !== $excludeSpaceId) - ->sortBy(fn (MakhzanFileLocation $l) => $l->role === LocationRole::Primary ? 0 : 1); + ->filter(fn (StorelyFileLocation $l) => $l->space !== null && $l->space->status !== SpaceStatus::Disabled && $l->storely_space_id !== $excludeSpaceId) + ->sortBy(fn (StorelyFileLocation $l) => $l->role === LocationRole::Primary ? 0 : 1); foreach ($locations as $location) { - /** @var MakhzanSpace $space */ + /** @var StorelySpace $space */ $space = $location->space; try { return ['stream' => $this->drivers->make($space)->read($location->locator), 'space' => $space]; - } catch (MakhzanException) { + } catch (StorelyException) { continue; // failover to the next copy } } - throw new MakhzanException('No copy of the file is currently available.'); + throw new StorelyException('No copy of the file is currently available.'); } /** * Copies the file to another space and verifies the copy by SHA-256. Idempotent. */ - public function copyTo(MakhzanFile $file, MakhzanSpace $target, LocationRole $role = LocationRole::Mirror): MakhzanFileLocation + public function copyTo(StorelyFile $file, StorelySpace $target, LocationRole $role = LocationRole::Mirror): StorelyFileLocation { - if ($existing = MakhzanFileLocation::query()->where('makhzan_file_id', $file->id)->where('makhzan_space_id', $target->id)->first()) { + if ($existing = StorelyFileLocation::query()->where('storely_file_id', $file->id)->where('storely_space_id', $target->id)->first()) { return $existing; } if (! $target->status->acceptsWrites()) { - throw new MakhzanException('The target space does not accept writes.'); + throw new StorelyException('The target space does not accept writes.'); } if (($max = $target->driver->maxFileBytes()) !== null && $file->size > $max) { - throw new MakhzanException('The file is larger than this space\'s per-file limit.'); + throw new StorelyException('The file is larger than this space\'s per-file limit.'); } $source = $this->read($file, $target->id)['stream']; @@ -152,11 +152,11 @@ public function copyTo(MakhzanFile $file, MakhzanSpace $target, LocationRole $ro try { [$sha, $size] = $this->hashStream($driver->read($locator)); if ($sha !== $file->sha256 || $size !== $file->size) { - throw new MakhzanException('SHA-256 verification of the new copy failed.'); + throw new StorelyException('SHA-256 verification of the new copy failed.'); } - return DB::transaction(function () use ($file, $target, $locator, $role): MakhzanFileLocation { - $dup = MakhzanFileLocation::query()->where('makhzan_file_id', $file->id)->where('makhzan_space_id', $target->id)->lockForUpdate()->first(); + return DB::transaction(function () use ($file, $target, $locator, $role): StorelyFileLocation { + $dup = StorelyFileLocation::query()->where('storely_file_id', $file->id)->where('storely_space_id', $target->id)->lockForUpdate()->first(); return $dup ?? $this->addLocation($file, $target, $locator, $role); }); @@ -169,12 +169,12 @@ public function copyTo(MakhzanFile $file, MakhzanSpace $target, LocationRole $ro /** * Moves one location to another space. The old copy is deleted only after the new one is verified. */ - public function move(MakhzanFileLocation $from, MakhzanSpace $to): void + public function move(StorelyFileLocation $from, StorelySpace $to): void { - if ($from->makhzan_space_id === $to->id) { + if ($from->storely_space_id === $to->id) { return; } - /** @var MakhzanFile $file */ + /** @var StorelyFile $file */ $file = $from->file; $new = $this->copyTo($file, $to, $from->role); @@ -182,21 +182,21 @@ public function move(MakhzanFileLocation $from, MakhzanSpace $to): void $new->forceFill(['role' => LocationRole::Primary])->save(); } - /** @var MakhzanSpace $fromSpace */ + /** @var StorelySpace $fromSpace */ $fromSpace = $from->space; $this->drivers->make($fromSpace)->delete($from->locator); $from->delete(); } /** Removes one copy. The last copy of a live file cannot be removed this way. */ - public function removeLocation(MakhzanFileLocation $location): void + public function removeLocation(StorelyFileLocation $location): void { - /** @var MakhzanFile $file */ + /** @var StorelyFile $file */ $file = $location->file; if ($file->locations()->count() <= 1) { - throw new MakhzanException('This is the last copy of the file.'); + throw new StorelyException('This is the last copy of the file.'); } - /** @var MakhzanSpace $space */ + /** @var StorelySpace $space */ $space = $location->space; $this->drivers->make($space)->delete($location->locator); $wasPrimary = $location->role === LocationRole::Primary; @@ -207,18 +207,18 @@ public function removeLocation(MakhzanFileLocation $location): void } } - private function record(string $sha, int $size, string $name, ?string $mime, MakhzanSpace $space, StorageDriver $driver, string $locator): MakhzanFile + private function record(string $sha, int $size, string $name, ?string $mime, StorelySpace $space, StorageDriver $driver, string $locator): StorelyFile { - return DB::transaction(function () use ($sha, $size, $name, $mime, $space, $driver, $locator): MakhzanFile { + return DB::transaction(function () use ($sha, $size, $name, $mime, $space, $driver, $locator): StorelyFile { // Another upload of the same bytes may have won while we were uploading. - $winner = MakhzanFile::query()->where('sha256', $sha)->where('size', $size)->lockForUpdate()->first(); + $winner = StorelyFile::query()->where('sha256', $sha)->where('size', $size)->lockForUpdate()->first(); if ($winner !== null && $winner->locations()->exists()) { $this->quietDelete($driver, $locator); return $winner; } - $file = $winner ?? new MakhzanFile; + $file = $winner ?? new StorelyFile; $file->fill(['original_name' => $this->cleanName($name), 'mime' => $mime]); $file->sha256 = $sha; $file->size = $size; @@ -230,13 +230,13 @@ private function record(string $sha, int $size, string $name, ?string $mime, Mak }); } - private function afterStore(MakhzanSpace $space, MakhzanFile $stored, int $size, ?MakhzanSpace $mirror): void + private function afterStore(StorelySpace $space, StorelyFile $stored, int $size, ?StorelySpace $mirror): void { if ($mirror !== null) { MirrorFileJob::dispatch($stored->id, $mirror->id)->afterCommit(); } - $location = $stored->locations()->where('makhzan_space_id', $space->id)->first(); + $location = $stored->locations()->where('storely_space_id', $space->id)->first(); if ($location !== null) { FileStored::dispatch($stored, $location, false); } @@ -245,7 +245,7 @@ private function afterStore(MakhzanSpace $space, MakhzanFile $stored, int $size, } /** Fires SpaceCapacityWarning only when this write crossed the configured line. */ - private function warnIfCapacityCrossed(MakhzanSpace $space, int $justWritten): void + private function warnIfCapacityCrossed(StorelySpace $space, int $justWritten): void { if ($space->capacity_bytes === null) { return; @@ -266,13 +266,13 @@ private function warnIfCapacityCrossed(MakhzanSpace $space, int $justWritten): v * A short-lived URL to one live copy, from the first space (in fill order) * whose driver can sign one. Null when no copy can produce a URL. */ - public function temporaryUrl(MakhzanFile $file, int $minutes = 5): ?string + public function temporaryUrl(StorelyFile $file, int $minutes = 5): ?string { $expiresAt = now()->addMinutes(max(1, min(10080, $minutes))); $locations = $file->locations()->with('space')->get() - ->sortBy(fn (MakhzanFileLocation $l) => $l->space instanceof MakhzanSpace ? $l->space->priority : PHP_INT_MAX); + ->sortBy(fn (StorelyFileLocation $l) => $l->space instanceof StorelySpace ? $l->space->priority : PHP_INT_MAX); foreach ($locations as $location) { - /** @var MakhzanSpace|null $space */ + /** @var StorelySpace|null $space */ $space = $location->space; if ($space === null) { continue; @@ -283,7 +283,7 @@ public function temporaryUrl(MakhzanFile $file, int $minutes = 5): ?string } try { return $driver->temporaryUrl($location->locator, $expiresAt); - } catch (MakhzanException) { + } catch (StorelyException) { continue; // this copy cannot sign; try the next one } } @@ -293,9 +293,9 @@ public function temporaryUrl(MakhzanFile $file, int $minutes = 5): ?string /** * Soft-deletes the file. Remote copies stay in place until forceDelete() or - * the makhzan:prune command removes them. + * the storely:prune command removes them. */ - public function delete(MakhzanFile $file): void + public function delete(StorelyFile $file): void { $file->delete(); } @@ -304,13 +304,13 @@ public function delete(MakhzanFile $file): void * Undoes a soft delete. The remote copies were left in place by delete(), so * restoring only touches the record; it throws when every copy is already gone. */ - public function restore(MakhzanFile $file): MakhzanFile + public function restore(StorelyFile $file): StorelyFile { if (! $file->trashed()) { return $file; } if ($file->locations()->count() === 0) { - throw new MakhzanException('The file has no copies left to restore.'); + throw new StorelyException('The file has no copies left to restore.'); } $file->restore(); @@ -321,10 +321,10 @@ public function restore(MakhzanFile $file): MakhzanFile * Permanently removes the file: every remote copy is deleted (best effort), * then the database rows go. */ - public function forceDelete(MakhzanFile $file): void + public function forceDelete(StorelyFile $file): void { foreach ($file->locations()->withTrashed()->with('space')->get() as $location) { - /** @var MakhzanSpace|null $space */ + /** @var StorelySpace|null $space */ $space = $location->space; if ($space !== null) { $this->quietDelete($this->drivers->make($space), $location->locator); @@ -334,23 +334,23 @@ public function forceDelete(MakhzanFile $file): void $file->forceDelete(); } - private function findLive(string $sha, int $size): ?MakhzanFile + private function findLive(string $sha, int $size): ?StorelyFile { - $file = MakhzanFile::query()->where('sha256', $sha)->where('size', $size)->first(); + $file = StorelyFile::query()->where('sha256', $sha)->where('size', $size)->first(); return $file && $file->locations()->exists() ? $file : null; } - private function addLocation(MakhzanFile $file, MakhzanSpace $space, string $locator, LocationRole $role): MakhzanFileLocation + private function addLocation(StorelyFile $file, StorelySpace $space, string $locator, LocationRole $role): StorelyFileLocation { // The unique (file, space) row may exist soft-deleted from an earlier move: reuse it. - $location = MakhzanFileLocation::withTrashed()->where('makhzan_file_id', $file->id)->where('makhzan_space_id', $space->id)->first(); + $location = StorelyFileLocation::withTrashed()->where('storely_file_id', $file->id)->where('storely_space_id', $space->id)->first(); if ($location?->trashed()) { $location->restore(); } - $location ??= new MakhzanFileLocation; - $location->makhzan_file_id = $file->id; - $location->makhzan_space_id = $space->id; + $location ??= new StorelyFileLocation; + $location->storely_file_id = $file->id; + $location->storely_space_id = $space->id; $location->locator = $locator; $location->role = $role; $location->verified_at = now(); @@ -388,16 +388,16 @@ private function spool($stream): array { $path = tempnam(sys_get_temp_dir(), 'mkz'); if ($path === false) { - throw new MakhzanException('Could not create a temporary spool file.'); + throw new StorelyException('Could not create a temporary spool file.'); } $out = fopen($path, 'wb'); if ($out === false) { @unlink($path); - throw new MakhzanException('Could not open the spool file.'); + throw new StorelyException('Could not open the spool file.'); } $ctx = hash_init('sha256'); $size = 0; - $max = (int) config('makhzan.max_upload_bytes'); + $max = (int) config('storely.max_upload_bytes'); while (! feof($stream)) { $chunk = fread($stream, 1024 * 1024); if ($chunk === false || $chunk === '') { @@ -407,7 +407,7 @@ private function spool($stream): array if ($size > $max) { fclose($out); @unlink($path); - throw new MakhzanException('The file is larger than the allowed maximum.'); + throw new StorelyException('The file is larger than the allowed maximum.'); } hash_update($ctx, $chunk); fwrite($out, $chunk); @@ -415,7 +415,7 @@ private function spool($stream): array fclose($out); if ($size === 0) { @unlink($path); - throw new MakhzanException('The file is empty.'); + throw new StorelyException('The file is empty.'); } return [$path, hash_final($ctx), $size]; diff --git a/src/Services/GcService.php b/src/Services/GcService.php index dfb0032..8d0d5ab 100644 --- a/src/Services/GcService.php +++ b/src/Services/GcService.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace Makhzan\Services; +namespace Storely\Services; -use Makhzan\DriverFactory; -use Makhzan\Models\MakhzanFile; -use Makhzan\Models\MakhzanFileLocation; -use Makhzan\Models\MakhzanSpace; +use Storely\DriverFactory; +use Storely\Models\StorelyFile; +use Storely\Models\StorelyFileLocation; +use Storely\Models\StorelySpace; use Throwable; /** @@ -28,9 +28,9 @@ public function collect(bool $checkRemote = false, bool $purge = false, bool $dr $deadSpace = 0; $remoteMissing = 0; - $deletedSpaceIds = MakhzanSpace::onlyTrashed()->pluck('id'); - foreach (MakhzanFileLocation::query()->whereIn('makhzan_space_id', $deletedSpaceIds)->cursor() as $location) { - /** @var MakhzanFileLocation $location */ + $deletedSpaceIds = StorelySpace::onlyTrashed()->pluck('id'); + foreach (StorelyFileLocation::query()->whereIn('storely_space_id', $deletedSpaceIds)->cursor() as $location) { + /** @var StorelyFileLocation $location */ $deadSpace++; if (! $dryRun) { $location->forceDelete(); @@ -38,9 +38,9 @@ public function collect(bool $checkRemote = false, bool $purge = false, bool $dr } if ($checkRemote) { - foreach (MakhzanFileLocation::query()->with('space')->orderBy('id')->cursor() as $location) { - /** @var MakhzanFileLocation $location */ - /** @var MakhzanSpace|null $space */ + foreach (StorelyFileLocation::query()->with('space')->orderBy('id')->cursor() as $location) { + /** @var StorelyFileLocation $location */ + /** @var StorelySpace|null $space */ $space = $location->space; if ($space === null) { continue; @@ -61,9 +61,9 @@ public function collect(bool $checkRemote = false, bool $purge = false, bool $dr $emptyFiles = 0; $purged = 0; - $fileQuery = MakhzanFile::query()->whereDoesntHave('locations')->orderBy('id'); + $fileQuery = StorelyFile::query()->whereDoesntHave('locations')->orderBy('id'); foreach ($fileQuery->cursor() as $file) { - /** @var MakhzanFile $file */ + /** @var StorelyFile $file */ $emptyFiles++; if ($purge) { $purged++; diff --git a/src/Services/HealthService.php b/src/Services/HealthService.php index 1eee08e..00b18f8 100644 --- a/src/Services/HealthService.php +++ b/src/Services/HealthService.php @@ -2,17 +2,17 @@ declare(strict_types=1); -namespace Makhzan\Services; +namespace Storely\Services; use Illuminate\Support\Collection; -use Makhzan\Models\MakhzanSpace; +use Storely\Models\StorelySpace; /** Live health checks, one space or all of them. Wire checkAll() into the scheduler. */ class HealthService { public function __construct(private readonly SpaceService $spaces) {} - public function check(MakhzanSpace $space): MakhzanSpace + public function check(StorelySpace $space): StorelySpace { return $this->spaces->check($space); } @@ -20,24 +20,24 @@ public function check(MakhzanSpace $space): MakhzanSpace /** * Checks every non-deleted space. Returns the spaces keyed by id with the outcome. * - * @return Collection + * @return Collection */ public function checkAll(): Collection { - return MakhzanSpace::query()->orderBy('priority')->orderBy('id')->get() - ->map(fn (MakhzanSpace $space) => $this->spaces->check($space)) + return StorelySpace::query()->orderBy('priority')->orderBy('id')->get() + ->map(fn (StorelySpace $space) => $this->spaces->check($space)) ->keyBy('id'); } /** * Spaces that currently serve files but whose last check failed. * - * @return Collection + * @return Collection */ public function unhealthy(): Collection { - return MakhzanSpace::query()->get() - ->filter(fn (MakhzanSpace $space) => $space->status->needsPassingCheck() && ! $space->hasPassingCheck()) + return StorelySpace::query()->get() + ->filter(fn (StorelySpace $space) => $space->status->needsPassingCheck() && ! $space->hasPassingCheck()) ->values(); } } diff --git a/src/Services/RuleService.php b/src/Services/RuleService.php index d154bc7..8b6bb87 100644 --- a/src/Services/RuleService.php +++ b/src/Services/RuleService.php @@ -2,37 +2,37 @@ declare(strict_types=1); -namespace Makhzan\Services; +namespace Storely\Services; use Illuminate\Validation\ValidationException; -use Makhzan\Models\MakhzanRoutingRule; -use Makhzan\Models\MakhzanSpace; +use Storely\Models\StorelyRoutingRule; +use Storely\Models\StorelySpace; /** CRUD and validation for routing rules. */ class RuleService { /** - * @param array{name?: mixed, priority?: mixed, category?: mixed, min_size?: mixed, max_size?: mixed, makhzan_space_id?: mixed, mirror_space_id?: mixed, is_active?: mixed} $data + * @param array{name?: mixed, priority?: mixed, category?: mixed, min_size?: mixed, max_size?: mixed, storely_space_id?: mixed, mirror_space_id?: mixed, is_active?: mixed} $data */ - public function create(array $data): MakhzanRoutingRule + public function create(array $data): StorelyRoutingRule { - $rule = new MakhzanRoutingRule; + $rule = new StorelyRoutingRule; $rule->forceFill($this->validated($data))->save(); return $rule; } /** - * @param array{name?: mixed, priority?: mixed, category?: mixed, min_size?: mixed, max_size?: mixed, makhzan_space_id?: mixed, mirror_space_id?: mixed, is_active?: mixed} $data + * @param array{name?: mixed, priority?: mixed, category?: mixed, min_size?: mixed, max_size?: mixed, storely_space_id?: mixed, mirror_space_id?: mixed, is_active?: mixed} $data */ - public function update(MakhzanRoutingRule $rule, array $data): MakhzanRoutingRule + public function update(StorelyRoutingRule $rule, array $data): StorelyRoutingRule { $rule->forceFill($this->validated($data, $rule))->save(); return $rule; } - public function delete(MakhzanRoutingRule $rule): void + public function delete(StorelyRoutingRule $rule): void { $rule->delete(); } @@ -41,11 +41,11 @@ public function delete(MakhzanRoutingRule $rule): void * @param array $d * @return array */ - private function validated(array $d, ?MakhzanRoutingRule $existing = null): array + private function validated(array $d, ?StorelyRoutingRule $existing = null): array { /** @var array $cur current values used as fallbacks on update */ $cur = $existing === null ? [] : $existing->only([ - 'name', 'priority', 'category', 'min_size', 'max_size', 'makhzan_space_id', 'mirror_space_id', 'is_active', + 'name', 'priority', 'category', 'min_size', 'max_size', 'storely_space_id', 'mirror_space_id', 'is_active', ]); $pick = fn (string $key, mixed $default): mixed => array_key_exists($key, $d) ? $d[$key] : ($cur[$key] ?? $default); @@ -53,7 +53,7 @@ private function validated(array $d, ?MakhzanRoutingRule $existing = null): arra if (mb_strlen($name) < 2 || mb_strlen($name) > 100) { throw ValidationException::withMessages(['name' => 'The rule name must be between 2 and 100 characters.']); } - $category = trim((string) $pick('category', MakhzanRoutingRule::ANY)); + $category = trim((string) $pick('category', StorelyRoutingRule::ANY)); if ($category === '' || mb_strlen($category) > 50 || ! preg_match('/^[A-Za-z0-9_-]+$/', $category)) { throw ValidationException::withMessages(['category' => 'The category may only contain letters, numbers, dashes and underscores (max 50).']); } @@ -64,13 +64,13 @@ private function validated(array $d, ?MakhzanRoutingRule $existing = null): arra if (($min !== null && $min < 0) || ($max !== null && $max < 1) || ($min !== null && $max !== null && $min > $max)) { throw ValidationException::withMessages(['max_size' => 'The size range is invalid.']); } - $spaceId = (int) $pick('makhzan_space_id', 0); - if (MakhzanSpace::find($spaceId) === null) { - throw ValidationException::withMessages(['makhzan_space_id' => 'Choose a space.']); + $spaceId = (int) $pick('storely_space_id', 0); + if (StorelySpace::find($spaceId) === null) { + throw ValidationException::withMessages(['storely_space_id' => 'Choose a space.']); } $mirrorRaw = $pick('mirror_space_id', null); $mirrorId = $mirrorRaw === null || $mirrorRaw === '' || (int) $mirrorRaw === 0 ? null : (int) $mirrorRaw; - if ($mirrorId !== null && ($mirrorId === $spaceId || MakhzanSpace::find($mirrorId) === null)) { + if ($mirrorId !== null && ($mirrorId === $spaceId || StorelySpace::find($mirrorId) === null)) { throw ValidationException::withMessages(['mirror_space_id' => 'The mirror must be a different, existing space.']); } @@ -80,7 +80,7 @@ private function validated(array $d, ?MakhzanRoutingRule $existing = null): arra 'category' => $category, 'min_size' => $min, 'max_size' => $max, - 'makhzan_space_id' => $spaceId, + 'storely_space_id' => $spaceId, 'mirror_space_id' => $mirrorId, 'is_active' => (bool) $pick('is_active', true), ]; diff --git a/src/Services/SpaceResolver.php b/src/Services/SpaceResolver.php index 9ce51c1..518f4e3 100644 --- a/src/Services/SpaceResolver.php +++ b/src/Services/SpaceResolver.php @@ -2,12 +2,12 @@ declare(strict_types=1); -namespace Makhzan\Services; +namespace Storely\Services; -use Makhzan\Enums\SpaceStatus; -use Makhzan\Exceptions\NoUsableSpaceException; -use Makhzan\Models\MakhzanRoutingRule; -use Makhzan\Models\MakhzanSpace; +use Storely\Enums\SpaceStatus; +use Storely\Exceptions\NoUsableSpaceException; +use Storely\Models\StorelyRoutingRule; +use Storely\Models\StorelySpace; /** * Chooses the spaces a new file is written to. Active routing rules are evaluated @@ -20,14 +20,14 @@ class SpaceResolver /** * Ordered write candidates for a file, each with the mirror that applies. * - * @return list + * @return list */ public function candidates(int $size, string $category = 'general'): array { $picked = []; $out = []; - foreach (MakhzanRoutingRule::query()->where('is_active', true)->orderBy('priority')->orderBy('id')->get() as $rule) { + foreach (StorelyRoutingRule::query()->where('is_active', true)->orderBy('priority')->orderBy('id')->get() as $rule) { if (! $rule->matches($size, $category)) { continue; } @@ -53,7 +53,7 @@ public function candidates(int $size, string $category = 'general'): array } /** The first candidate space, or a NoUsableSpaceException naming the reason. */ - public function resolve(int $size, string $category = 'general'): MakhzanSpace + public function resolve(int $size, string $category = 'general'): StorelySpace { $candidates = $this->candidates($size, $category); if ($candidates === []) { @@ -63,21 +63,21 @@ public function resolve(int $size, string $category = 'general'): MakhzanSpace return $candidates[0]['space']; } - /** @return list */ + /** @return list */ private function writableSpaces(int $size): array { - /** @var list */ - return MakhzanSpace::query() + /** @var list */ + return StorelySpace::query() ->where('status', SpaceStatus::Active->value) ->orderBy('priority') ->orderBy('id') ->get() - ->filter(fn (MakhzanSpace $space) => $this->writable($space, $size)) + ->filter(fn (StorelySpace $space) => $this->writable($space, $size)) ->values() ->all(); } - public function writable(MakhzanSpace $space, int $size): bool + public function writable(StorelySpace $space, int $size): bool { if (! $space->status->acceptsWrites() || ! $space->hasPassingCheck()) { return false; @@ -91,16 +91,16 @@ public function writable(MakhzanSpace $space, int $size): bool } /** True when the space's declared capacity can still hold the file. Unknown capacity always fits. */ - public function fitsCapacity(MakhzanSpace $space, int $size): bool + public function fitsCapacity(StorelySpace $space, int $size): bool { if ($space->capacity_bytes === null) { return true; } $used = (int) $space->locations() - ->join('makhzan_files', 'makhzan_files.id', '=', 'makhzan_file_locations.makhzan_file_id') - ->whereNull('makhzan_file_locations.deleted_at') - ->whereNull('makhzan_files.deleted_at') - ->sum('makhzan_files.size'); + ->join('storely_files', 'storely_files.id', '=', 'storely_file_locations.storely_file_id') + ->whereNull('storely_file_locations.deleted_at') + ->whereNull('storely_files.deleted_at') + ->sum('storely_files.size'); return $used + $size <= $space->capacity_bytes; } diff --git a/src/Services/SpaceService.php b/src/Services/SpaceService.php index 8e036c0..1069947 100644 --- a/src/Services/SpaceService.php +++ b/src/Services/SpaceService.php @@ -2,16 +2,16 @@ declare(strict_types=1); -namespace Makhzan\Services; +namespace Storely\Services; use Illuminate\Support\Facades\DB; use Illuminate\Validation\ValidationException; -use Makhzan\DriverFactory; -use Makhzan\Enums\SpaceDriver; -use Makhzan\Enums\SpaceStatus; -use Makhzan\Events\SpaceChecked; -use Makhzan\Exceptions\MakhzanException; -use Makhzan\Models\MakhzanSpace; +use Storely\DriverFactory; +use Storely\Enums\SpaceDriver; +use Storely\Enums\SpaceStatus; +use Storely\Events\SpaceChecked; +use Storely\Exceptions\StorelyException; +use Storely\Models\StorelySpace; /** * Space registry. Credentials are encrypted at rest and never returned. A space serves @@ -22,9 +22,9 @@ class SpaceService public function __construct(private readonly DriverFactory $drivers) {} /** @param array $credentials */ - public function create(string $name, SpaceDriver $driver, array $credentials, int $priority = 100, ?int $capacityBytes = null): MakhzanSpace + public function create(string $name, SpaceDriver $driver, array $credentials, int $priority = 100, ?int $capacityBytes = null): StorelySpace { - $space = new MakhzanSpace(['name' => $this->cleanName($name)]); + $space = new StorelySpace(['name' => $this->cleanName($name)]); $space->driver = $driver; $space->status = SpaceStatus::Disabled; $space->priority = $this->cleanPriority($priority); @@ -42,13 +42,13 @@ public function create(string $name, SpaceDriver $driver, array $credentials, in * * @param array $credentials */ - public function update(MakhzanSpace $space, string $name, array $credentials): MakhzanSpace + public function update(StorelySpace $space, string $name, array $credentials): StorelySpace { $space->name = $this->cleanName($name); $merged = $this->cleanCredentials($space->driver, $credentials, $space->credentials); - return DB::transaction(function () use ($space, $merged): MakhzanSpace { - $fresh = MakhzanSpace::lockForUpdate()->findOrFail($space->id); + return DB::transaction(function () use ($space, $merged): StorelySpace { + $fresh = StorelySpace::lockForUpdate()->findOrFail($space->id); $changed = $merged !== $fresh->credentials; $fresh->name = $space->name; $fresh->credentials = $merged; @@ -65,12 +65,12 @@ public function update(MakhzanSpace $space, string $name, array $credentials): M } /** Runs the live check and records the result against the exact credentials checked. */ - public function check(MakhzanSpace $space): MakhzanSpace + public function check(StorelySpace $space): StorelySpace { try { $message = $this->drivers->make($space)->test(); $ok = true; - } catch (MakhzanException $e) { + } catch (StorelyException $e) { $message = $e->getMessage(); $ok = false; } @@ -89,7 +89,7 @@ public function check(MakhzanSpace $space): MakhzanSpace return $space; } - public function setStatus(MakhzanSpace $space, SpaceStatus $status): MakhzanSpace + public function setStatus(StorelySpace $space, SpaceStatus $status): StorelySpace { if ($status->needsPassingCheck() && ! $space->hasPassingCheck()) { throw ValidationException::withMessages(['status' => 'The live check must pass on the current credentials before the space can serve files.']); @@ -101,7 +101,7 @@ public function setStatus(MakhzanSpace $space, SpaceStatus $status): MakhzanSpac return $space; } - public function setPriority(MakhzanSpace $space, int $priority): MakhzanSpace + public function setPriority(StorelySpace $space, int $priority): StorelySpace { $space->priority = $this->cleanPriority($priority); $space->save(); @@ -110,7 +110,7 @@ public function setPriority(MakhzanSpace $space, int $priority): MakhzanSpace } /** Capacity drives the usage meter and the capacity-warning event. Null means unknown. */ - public function setCapacity(MakhzanSpace $space, ?int $bytes): MakhzanSpace + public function setCapacity(StorelySpace $space, ?int $bytes): StorelySpace { $space->capacity_bytes = $this->cleanCapacity($bytes); $space->save(); @@ -118,7 +118,7 @@ public function setCapacity(MakhzanSpace $space, ?int $bytes): MakhzanSpace return $space; } - public function setMirror(MakhzanSpace $space, ?MakhzanSpace $mirror): MakhzanSpace + public function setMirror(StorelySpace $space, ?StorelySpace $mirror): StorelySpace { $this->validateMirror($space, $mirror?->id); $space->mirror_space_id = $mirror?->id; @@ -128,14 +128,14 @@ public function setMirror(MakhzanSpace $space, ?MakhzanSpace $mirror): MakhzanSp } /** @return array{files: int, bytes: int, percent: int|null, warning: bool} */ - public function usage(MakhzanSpace $space): array + public function usage(StorelySpace $space): array { - $row = DB::table('makhzan_file_locations') - ->join('makhzan_files', 'makhzan_files.id', '=', 'makhzan_file_locations.makhzan_file_id') - ->where('makhzan_file_locations.makhzan_space_id', $space->id) - ->whereNull('makhzan_file_locations.deleted_at') - ->whereNull('makhzan_files.deleted_at') - ->selectRaw('count(*) as n, coalesce(sum(makhzan_files.size), 0) as b') + $row = DB::table('storely_file_locations') + ->join('storely_files', 'storely_files.id', '=', 'storely_file_locations.storely_file_id') + ->where('storely_file_locations.storely_space_id', $space->id) + ->whereNull('storely_file_locations.deleted_at') + ->whereNull('storely_files.deleted_at') + ->selectRaw('count(*) as n, coalesce(sum(storely_files.size), 0) as b') ->first(); $bytes = (int) ($row->b ?? 0); $percent = $space->capacity_bytes ? (int) floor($bytes / $space->capacity_bytes * 100) : null; @@ -156,14 +156,14 @@ public function usage(MakhzanSpace $space): array public function usageAll(): array { $out = []; - foreach (MakhzanSpace::query()->orderBy('priority')->orderBy('id')->get() as $space) { + foreach (StorelySpace::query()->orderBy('priority')->orderBy('id')->get() as $space) { $out[$space->id] = $this->usage($space); } return $out; } - public function delete(MakhzanSpace $space): void + public function delete(StorelySpace $space): void { if ($space->status !== SpaceStatus::Disabled) { throw ValidationException::withMessages(['status' => 'Disable the space before deleting it.']); @@ -177,16 +177,16 @@ public function delete(MakhzanSpace $space): void public function warningPercent(): int { - return max(1, min(100, (int) config('makhzan.capacity_warning_percent', 80))); + return max(1, min(100, (int) config('storely.capacity_warning_percent', 80))); } - private function validateMirror(?MakhzanSpace $space, ?int $mirrorId): void + private function validateMirror(?StorelySpace $space, ?int $mirrorId): void { if ($mirrorId !== null) { if ($space !== null && $mirrorId === $space->id) { throw ValidationException::withMessages(['mirror' => 'A space cannot mirror itself.']); } - if (MakhzanSpace::find($mirrorId) === null) { + if (StorelySpace::find($mirrorId) === null) { throw ValidationException::withMessages(['mirror' => 'The mirror space does not exist.']); } } diff --git a/src/Makhzan.php b/src/Storely.php similarity index 71% rename from src/Makhzan.php rename to src/Storely.php index bc45d44..bf5e469 100644 --- a/src/Makhzan.php +++ b/src/Storely.php @@ -2,23 +2,23 @@ declare(strict_types=1); -namespace Makhzan; - -use Makhzan\Enums\SpaceDriver; -use Makhzan\Models\MakhzanFile; -use Makhzan\Models\MakhzanMove; -use Makhzan\Models\MakhzanSpace; -use Makhzan\Services\DrainService; -use Makhzan\Services\FileStoreService; -use Makhzan\Services\GcService; -use Makhzan\Services\HealthService; -use Makhzan\Services\RuleService; -use Makhzan\Services\SpaceService; +namespace Storely; + +use Storely\Enums\SpaceDriver; +use Storely\Models\StorelyFile; +use Storely\Models\StorelyMove; +use Storely\Models\StorelySpace; +use Storely\Services\DrainService; +use Storely\Services\FileStoreService; +use Storely\Services\GcService; +use Storely\Services\HealthService; +use Storely\Services\RuleService; +use Storely\Services\SpaceService; /** - * Makhzan entry point. Wraps the services behind one manager for the facade and DI. + * Storely entry point. Wraps the services behind one manager for the facade and DI. */ -class Makhzan +class Storely { public function __construct( private readonly SpaceService $spaces, @@ -59,7 +59,7 @@ public function rules(): RuleService * * @param resource $stream */ - public function store($stream, string $name, ?string $mime = null, string $category = 'general'): MakhzanFile + public function store($stream, string $name, ?string $mime = null, string $category = 'general'): StorelyFile { return $this->files->store($stream, $name, $mime, $category); } @@ -70,25 +70,25 @@ public function gc(): GcService } /** A short-lived URL to one live copy, or null when no space can sign one. */ - public function temporaryUrl(MakhzanFile $file, int $minutes = 5): ?string + public function temporaryUrl(StorelyFile $file, int $minutes = 5): ?string { return $this->files->temporaryUrl($file, $minutes); } /** Undoes a soft delete; throws when no copy is left to restore. */ - public function restore(MakhzanFile $file): MakhzanFile + public function restore(StorelyFile $file): StorelyFile { return $this->files->restore($file); } - /** Soft-deletes the file; remote copies stay until forceDelete() or makhzan:prune. */ - public function delete(MakhzanFile $file): void + /** Soft-deletes the file; remote copies stay until forceDelete() or storely:prune. */ + public function delete(StorelyFile $file): void { $this->files->delete($file); } /** Permanently removes the file and every remote copy. */ - public function forceDelete(MakhzanFile $file): void + public function forceDelete(StorelyFile $file): void { $this->files->forceDelete($file); } @@ -96,15 +96,15 @@ public function forceDelete(MakhzanFile $file): void /** * Opens the file for reading, failing over across its copies. * - * @return array{stream: resource, space: MakhzanSpace} + * @return array{stream: resource, space: StorelySpace} */ - public function read(MakhzanFile $file): array + public function read(StorelyFile $file): array { return $this->files->read($file); } /** @param array $credentials */ - public function addSpace(string $name, SpaceDriver $driver, array $credentials, int $priority = 100, ?int $capacityBytes = null): MakhzanSpace + public function addSpace(string $name, SpaceDriver $driver, array $credentials, int $priority = 100, ?int $capacityBytes = null): StorelySpace { return $this->spaces->create($name, $driver, $credentials, $priority, $capacityBytes); } @@ -119,7 +119,7 @@ public function usage(): array return $this->spaces->usageAll(); } - public function drain(MakhzanSpace $from, MakhzanSpace $to, ?int $startedBy = null): MakhzanMove + public function drain(StorelySpace $from, StorelySpace $to, ?int $startedBy = null): StorelyMove { return $this->drain->start($from, $to, $startedBy); } diff --git a/src/MakhzanServiceProvider.php b/src/StorelyServiceProvider.php similarity index 58% rename from src/MakhzanServiceProvider.php rename to src/StorelyServiceProvider.php index 376170f..4453e9d 100644 --- a/src/MakhzanServiceProvider.php +++ b/src/StorelyServiceProvider.php @@ -2,24 +2,24 @@ declare(strict_types=1); -namespace Makhzan; +namespace Storely; use Illuminate\Support\ServiceProvider; -use Makhzan\Console\GcCommand; -use Makhzan\Console\HealthCheckCommand; -use Makhzan\Console\PruneCommand; -use Makhzan\Console\ReplicateCommand; -use Makhzan\Console\UsageCommand; -use Makhzan\Console\VerifyCommand; - -class MakhzanServiceProvider extends ServiceProvider +use Storely\Console\GcCommand; +use Storely\Console\HealthCheckCommand; +use Storely\Console\PruneCommand; +use Storely\Console\ReplicateCommand; +use Storely\Console\UsageCommand; +use Storely\Console\VerifyCommand; + +class StorelyServiceProvider extends ServiceProvider { public function register(): void { - $this->mergeConfigFrom(__DIR__.'/../config/makhzan.php', 'makhzan'); + $this->mergeConfigFrom(__DIR__.'/../config/storely.php', 'storely'); $this->app->singleton(DriverFactory::class); - $this->app->singleton(Makhzan::class); + $this->app->singleton(Storely::class); } public function boot(): void @@ -28,12 +28,12 @@ public function boot(): void if ($this->app->runningInConsole()) { $this->publishes([ - __DIR__.'/../config/makhzan.php' => config_path('makhzan.php'), - ], 'makhzan-config'); + __DIR__.'/../config/storely.php' => config_path('storely.php'), + ], 'storely-config'); $this->publishes([ __DIR__.'/../database/migrations' => database_path('migrations'), - ], 'makhzan-migrations'); + ], 'storely-migrations'); $this->commands([ GcCommand::class, diff --git a/tests/Feature/CommandsAndFacadeTest.php b/tests/Feature/CommandsAndFacadeTest.php index cc193e8..2193a94 100644 --- a/tests/Feature/CommandsAndFacadeTest.php +++ b/tests/Feature/CommandsAndFacadeTest.php @@ -3,26 +3,26 @@ declare(strict_types=1); use Illuminate\Support\Facades\Http; -use Makhzan\DriverFactory; -use Makhzan\Enums\SpaceDriver; -use Makhzan\Enums\SpaceStatus; -use Makhzan\Facades\Makhzan; -use Makhzan\Models\MakhzanFile; -use Makhzan\Services\FileStoreService; -use Makhzan\Services\SpaceService; +use Storely\DriverFactory; +use Storely\Enums\SpaceDriver; +use Storely\Enums\SpaceStatus; +use Storely\Facades\Storely; +use Storely\Models\StorelyFile; +use Storely\Services\FileStoreService; +use Storely\Services\SpaceService; it('exposes the manager through the facade', function () { - $space = Makhzan::addSpace('Facade Space', SpaceDriver::Local, ['root' => 'facade'], 10, 1000); - Makhzan::spaces()->check($space); - Makhzan::spaces()->setStatus($space->refresh(), SpaceStatus::Active); + $space = Storely::addSpace('Facade Space', SpaceDriver::Local, ['root' => 'facade'], 10, 1000); + Storely::spaces()->check($space); + Storely::spaces()->setStatus($space->refresh(), SpaceStatus::Active); - $file = Makhzan::store(streamOf('via-facade'), 'f.txt'); - expect($file)->toBeInstanceOf(MakhzanFile::class); + $file = Storely::store(streamOf('via-facade'), 'f.txt'); + expect($file)->toBeInstanceOf(StorelyFile::class); - $read = Makhzan::read($file); + $read = Storely::read($file); expect(stream_get_contents($read['stream']))->toBe('via-facade'); - $usage = Makhzan::usage(); + $usage = Storely::usage(); expect($usage[$space->id]['bytes'])->toBe(10); }); @@ -31,7 +31,7 @@ makeLocalSpace('Cmd B', 20); app(FileStoreService::class)->store(streamOf('cmd-bytes'), 'c.txt'); - $this->artisan('makhzan:usage') + $this->artisan('storely:usage') ->expectsOutputToContain('Cmd A') ->expectsOutputToContain('Cmd B') ->assertSuccessful(); @@ -40,9 +40,9 @@ it('runs the health command for all spaces and for one', function () { makeLocalSpace('HC', 10); - $this->artisan('makhzan:health')->assertSuccessful(); - $this->artisan('makhzan:health', ['--space' => 'HC'])->assertSuccessful(); - $this->artisan('makhzan:health', ['--space' => 'missing'])->assertFailed(); + $this->artisan('storely:health')->assertSuccessful(); + $this->artisan('storely:health', ['--space' => 'HC'])->assertSuccessful(); + $this->artisan('storely:health', ['--space' => 'missing'])->assertFailed(); }); it('fails the health command when a check fails', function () { @@ -50,7 +50,7 @@ $tg = $spaces->create('TgFail', SpaceDriver::Telegram, ['bot_token' => '1:x', 'chat_id' => '-100'], 10); Http::fake(['api.telegram.org/*' => Http::response(['ok' => false, 'description' => 'x'], 500)]); - $this->artisan('makhzan:health', ['--space' => 'TgFail'])->assertFailed(); + $this->artisan('storely:health', ['--space' => 'TgFail'])->assertFailed(); }); it('verifies stored copies and flags missing ones', function () { @@ -58,14 +58,14 @@ $files = app(FileStoreService::class); $file = $files->store(streamOf('verify-bytes'), 'v.txt'); - $this->artisan('makhzan:verify')->assertSuccessful(); - $this->artisan('makhzan:verify', ['--space' => 'VerifyMe'])->assertSuccessful(); - $this->artisan('makhzan:verify', ['--space' => 'nope'])->assertFailed(); + $this->artisan('storely:verify')->assertSuccessful(); + $this->artisan('storely:verify', ['--space' => 'VerifyMe'])->assertSuccessful(); + $this->artisan('storely:verify', ['--space' => 'nope'])->assertFailed(); // Delete the object behind the package's back. $driver = app(DriverFactory::class)->make($space); $driver->delete($file->locations()->first()->locator); - $this->artisan('makhzan:verify')->assertFailed(); + $this->artisan('storely:verify')->assertFailed(); expect($file->locations()->first()->verified_at)->not->toBeNull(); }); diff --git a/tests/Feature/DeleteAndPruneTest.php b/tests/Feature/DeleteAndPruneTest.php index 709a725..4d6d8c6 100644 --- a/tests/Feature/DeleteAndPruneTest.php +++ b/tests/Feature/DeleteAndPruneTest.php @@ -2,11 +2,11 @@ declare(strict_types=1); -use Makhzan\DriverFactory; -use Makhzan\Models\MakhzanFile; -use Makhzan\Models\MakhzanFileLocation; -use Makhzan\Services\FileStoreService; -use Makhzan\Services\SpaceService; +use Storely\DriverFactory; +use Storely\Models\StorelyFile; +use Storely\Models\StorelyFileLocation; +use Storely\Services\FileStoreService; +use Storely\Services\SpaceService; it('soft-deletes a file and drops it from usage', function () { $space = makeLocalSpace('Del', 10, 1000); @@ -17,8 +17,8 @@ $files->delete($file); - expect(MakhzanFile::find($file->id))->toBeNull() - ->and(MakhzanFile::withTrashed()->find($file->id))->not->toBeNull() + expect(StorelyFile::find($file->id))->toBeNull() + ->and(StorelyFile::withTrashed()->find($file->id))->not->toBeNull() ->and(app(SpaceService::class)->usage($space->refresh())['bytes'])->toBe(0); }); @@ -33,8 +33,8 @@ $files->forceDelete($file); expect($driver->exists($locator))->toBeFalse() - ->and(MakhzanFile::withTrashed()->find($file->id))->toBeNull() - ->and(MakhzanFileLocation::withTrashed()->where('makhzan_file_id', $file->id)->count())->toBe(0); + ->and(StorelyFile::withTrashed()->find($file->id))->toBeNull() + ->and(StorelyFileLocation::withTrashed()->where('storely_file_id', $file->id)->count())->toBe(0); }); it('prunes old trashed files and respects dry-run and the age cutoff', function () { @@ -44,12 +44,12 @@ $new = $files->store(streamOf('new'), 'new.txt'); $files->delete($old); $files->delete($new); - MakhzanFile::withTrashed()->whereKey($old->id)->update(['deleted_at' => now()->subDays(40)]); + StorelyFile::withTrashed()->whereKey($old->id)->update(['deleted_at' => now()->subDays(40)]); - $this->artisan('makhzan:prune', ['--days' => 30, '--dry-run' => true])->assertSuccessful(); - expect(MakhzanFile::withTrashed()->whereKey($old->id)->exists())->toBeTrue(); + $this->artisan('storely:prune', ['--days' => 30, '--dry-run' => true])->assertSuccessful(); + expect(StorelyFile::withTrashed()->whereKey($old->id)->exists())->toBeTrue(); - $this->artisan('makhzan:prune', ['--days' => 30])->assertSuccessful(); - expect(MakhzanFile::withTrashed()->whereKey($old->id)->exists())->toBeFalse() - ->and(MakhzanFile::withTrashed()->whereKey($new->id)->exists())->toBeTrue(); + $this->artisan('storely:prune', ['--days' => 30])->assertSuccessful(); + expect(StorelyFile::withTrashed()->whereKey($old->id)->exists())->toBeFalse() + ->and(StorelyFile::withTrashed()->whereKey($new->id)->exists())->toBeTrue(); }); diff --git a/tests/Feature/DrainMirrorHealthTest.php b/tests/Feature/DrainMirrorHealthTest.php index 06d8b7f..331e525 100644 --- a/tests/Feature/DrainMirrorHealthTest.php +++ b/tests/Feature/DrainMirrorHealthTest.php @@ -6,19 +6,19 @@ use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Queue; use Illuminate\Validation\ValidationException; -use Makhzan\Enums\MoveStatus; -use Makhzan\Enums\SpaceDriver; -use Makhzan\Enums\SpaceStatus; -use Makhzan\Events\MoveCompleted; -use Makhzan\Events\SpaceCapacityWarning; -use Makhzan\Events\SpaceChecked; -use Makhzan\Jobs\MirrorFileJob; -use Makhzan\Jobs\MoveLocationJob; -use Makhzan\Models\MakhzanFile; -use Makhzan\Services\DrainService; -use Makhzan\Services\FileStoreService; -use Makhzan\Services\HealthService; -use Makhzan\Services\SpaceService; +use Storely\Enums\MoveStatus; +use Storely\Enums\SpaceDriver; +use Storely\Enums\SpaceStatus; +use Storely\Events\MoveCompleted; +use Storely\Events\SpaceCapacityWarning; +use Storely\Events\SpaceChecked; +use Storely\Jobs\MirrorFileJob; +use Storely\Jobs\MoveLocationJob; +use Storely\Models\StorelyFile; +use Storely\Services\DrainService; +use Storely\Services\FileStoreService; +use Storely\Services\HealthService; +use Storely\Services\SpaceService; it('mirrors new writes to the mirror space through a queued job', function () { Queue::fake(); @@ -39,7 +39,7 @@ $file = app(FileStoreService::class)->store(streamOf('mirror-me-2'), 'm2.txt'); expect($file->locations()->count())->toBe(2) - ->and($file->locations()->where('makhzan_space_id', $mirror->id)->first()->role->value)->toBe('mirror'); + ->and($file->locations()->where('storely_space_id', $mirror->id)->first()->role->value)->toBe('mirror'); }); it('drains a space into another in the background and parks it', function () { @@ -50,7 +50,7 @@ $a = $files->store(streamOf('drain-a'), 'a.txt'); $b = $files->store(streamOf('drain-b'), 'b.txt'); - expect($a->locations()->first()->makhzan_space_id)->toBe($from->id); + expect($a->locations()->first()->storely_space_id)->toBe($from->id); $move = app(DrainService::class)->start($from, $to); @@ -60,8 +60,8 @@ ->and($move->failed)->toBe(0) ->and($from->refresh()->status)->toBe(SpaceStatus::Disabled) ->and($from->locations()->count())->toBe(0) - ->and($a->refresh()->locations()->first()->makhzan_space_id)->toBe($to->id) - ->and($b->refresh()->locations()->first()->makhzan_space_id)->toBe($to->id); + ->and($a->refresh()->locations()->first()->storely_space_id)->toBe($to->id) + ->and($b->refresh()->locations()->first()->storely_space_id)->toBe($to->id); Event::assertDispatched(MoveCompleted::class); }); @@ -232,7 +232,7 @@ app(SpaceService::class)->setMirror($main, $mirror); $file = app(FileStoreService::class)->store(streamOf('gone'), 'gone.txt'); - MakhzanFile::query()->whereKey($file->id)->forceDelete(); + StorelyFile::query()->whereKey($file->id)->forceDelete(); (new MirrorFileJob($file->id, $mirror->id))->handle(app(FileStoreService::class)); (new MirrorFileJob($file->id, 999999))->handle(app(FileStoreService::class)); diff --git a/tests/Feature/FileStoreTest.php b/tests/Feature/FileStoreTest.php index 693d1c1..60693af 100644 --- a/tests/Feature/FileStoreTest.php +++ b/tests/Feature/FileStoreTest.php @@ -4,20 +4,20 @@ use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Http; -use Makhzan\DriverFactory; -use Makhzan\Enums\LocationRole; -use Makhzan\Enums\SpaceDriver; -use Makhzan\Enums\SpaceStatus; -use Makhzan\Events\FileStored; -use Makhzan\Events\SpaceFailover; -use Makhzan\Exceptions\AllSpacesFailedException; -use Makhzan\Exceptions\MakhzanException; -use Makhzan\Exceptions\NoUsableSpaceException; -use Makhzan\Models\MakhzanFile; -use Makhzan\Services\FileStoreService; -use Makhzan\Services\SpaceService; - -function store(string $contents, string $name = 'file.txt'): MakhzanFile +use Storely\DriverFactory; +use Storely\Enums\LocationRole; +use Storely\Enums\SpaceDriver; +use Storely\Enums\SpaceStatus; +use Storely\Events\FileStored; +use Storely\Events\SpaceFailover; +use Storely\Exceptions\AllSpacesFailedException; +use Storely\Exceptions\NoUsableSpaceException; +use Storely\Exceptions\StorelyException; +use Storely\Models\StorelyFile; +use Storely\Services\FileStoreService; +use Storely\Services\SpaceService; + +function store(string $contents, string $name = 'file.txt'): StorelyFile { return app(FileStoreService::class)->store(streamOf($contents), $name); } @@ -30,7 +30,7 @@ function store(string $contents, string $name = 'file.txt'): MakhzanFile $file = store('priority-test', 'report.pdf'); expect($file->locations)->toHaveCount(1) - ->and($file->locations->first()->makhzan_space_id)->toBe($a->id) + ->and($file->locations->first()->storely_space_id)->toBe($a->id) ->and($file->sha256)->toBe(hash('sha256', 'priority-test')) ->and($file->original_name)->toBe('report.pdf'); @@ -47,7 +47,7 @@ function store(string $contents, string $name = 'file.txt'): MakhzanFile $second = store('same-bytes', 'b.txt'); expect($second->id)->toBe($first->id) - ->and(MakhzanFile::count())->toBe(1); + ->and(StorelyFile::count())->toBe(1); }); it('skips a full space and fills the next one', function () { @@ -56,7 +56,7 @@ function store(string $contents, string $name = 'file.txt'): MakhzanFile $file = store('more-than-five-bytes'); - expect($file->locations->first()->makhzan_space_id)->toBe($next->id); + expect($file->locations->first()->storely_space_id)->toBe($next->id); }); it('fails over to the next space when the first write fails', function () { @@ -71,7 +71,7 @@ function store(string $contents, string $name = 'file.txt'): MakhzanFile $file = store('failover-bytes'); - expect($file->locations->first()->makhzan_space_id)->toBe($local->id); + expect($file->locations->first()->storely_space_id)->toBe($local->id); Event::assertDispatched(SpaceFailover::class, fn ($e) => $e->from->id === $tg->id && $e->to->id === $local->id); }); @@ -97,14 +97,14 @@ function store(string $contents, string $name = 'file.txt'): MakhzanFile it('rejects empty and oversized uploads', function () { makeLocalSpace('Limits'); store(''); -})->throws(MakhzanException::class, 'empty'); +})->throws(StorelyException::class, 'empty'); it('enforces the configured upload limit', function () { - config()->set('makhzan.max_upload_bytes', 10); + config()->set('storely.max_upload_bytes', 10); makeLocalSpace('Limits2'); store(str_repeat('a', 11)); -})->throws(MakhzanException::class, 'maximum'); +})->throws(StorelyException::class, 'maximum'); it('respects the telegram per-file limit when routing', function () { Http::fake(['api.telegram.org/*' => Http::response(['ok' => true, 'result' => ['message_id' => 1, 'document' => ['file_id' => 'F']]])]); @@ -116,7 +116,7 @@ function store(string $contents, string $name = 'file.txt'): MakhzanFile $file = store(str_repeat('a', 21 * 1024 * 1024)); // over telegram's 20 MB cap - expect($file->locations->first()->makhzan_space_id)->toBe($local->id); + expect($file->locations->first()->storely_space_id)->toBe($local->id); }); it('reads through a mirror when the primary copy is gone', function () { @@ -129,7 +129,7 @@ function store(string $contents, string $name = 'file.txt'): MakhzanFile expect($file->locations()->count())->toBe(2); // Wipe the primary space's objects. - $primaryLocation = $file->locations()->where('makhzan_space_id', $a->id)->first(); + $primaryLocation = $file->locations()->where('storely_space_id', $a->id)->first(); $files->removeLocation($primaryLocation); $read = $files->read($file->refresh()); @@ -164,7 +164,7 @@ function store(string $contents, string $name = 'file.txt'): MakhzanFile $files->move($location, $b); expect($file->locations()->count())->toBe(1) - ->and($file->locations()->first()->makhzan_space_id)->toBe($b->id); + ->and($file->locations()->first()->storely_space_id)->toBe($b->id); $fromDriver = app(DriverFactory::class)->make($a); expect($fromDriver->exists($oldLocator))->toBeFalse(); }); @@ -174,7 +174,7 @@ function store(string $contents, string $name = 'file.txt'): MakhzanFile $file = store('last-copy'); app(FileStoreService::class)->removeLocation($file->locations()->first()); -})->throws(MakhzanException::class, 'last copy'); +})->throws(StorelyException::class, 'last copy'); it('sanitizes stored file names', function () { makeLocalSpace('Names', 10); diff --git a/tests/Feature/GcTest.php b/tests/Feature/GcTest.php index 9966cca..a54ef84 100644 --- a/tests/Feature/GcTest.php +++ b/tests/Feature/GcTest.php @@ -2,14 +2,14 @@ declare(strict_types=1); -use Makhzan\Contracts\StorageDriver; -use Makhzan\DriverFactory; -use Makhzan\Enums\LocationRole; -use Makhzan\Exceptions\MakhzanException; -use Makhzan\Models\MakhzanFile; -use Makhzan\Models\MakhzanFileLocation; -use Makhzan\Models\MakhzanSpace; -use Makhzan\Services\GcService; +use Storely\Contracts\StorageDriver; +use Storely\DriverFactory; +use Storely\Enums\LocationRole; +use Storely\Exceptions\StorelyException; +use Storely\Models\StorelyFile; +use Storely\Models\StorelyFileLocation; +use Storely\Models\StorelySpace; +use Storely\Services\GcService; function gcWith(StorageDriver $driver): GcService { @@ -17,7 +17,7 @@ function gcWith(StorageDriver $driver): GcService { public function __construct(private readonly StorageDriver $driver) {} - public function make(MakhzanSpace $space): StorageDriver + public function make(StorelySpace $space): StorageDriver { return $this->driver; } @@ -59,59 +59,59 @@ public function test(): string it('removes locations whose space was deleted', function () { $main = makeLocalSpace('GcMain'); $gone = makeLocalSpace('GcGone'); - $file = Makhzan\Facades\Makhzan::store(streamOf('two copies'), 'gc1.txt'); - $mirror = new MakhzanFileLocation; + $file = Storely\Facades\Storely::store(streamOf('two copies'), 'gc1.txt'); + $mirror = new StorelyFileLocation; $mirror->forceFill([ - 'makhzan_file_id' => $file->id, - 'makhzan_space_id' => $gone->id, + 'storely_file_id' => $file->id, + 'storely_space_id' => $gone->id, 'locator' => 'mirror-copy', 'role' => LocationRole::Mirror, ])->save(); - expect(MakhzanFileLocation::count())->toBe(2); + expect(StorelyFileLocation::count())->toBe(2); $gone->delete(); // soft-delete the space $result = app(GcService::class)->collect(); expect($result['dead_space_locations'])->toBe(1) - ->and(MakhzanFileLocation::count())->toBe(1) - ->and(MakhzanFileLocation::first()->makhzan_space_id)->toBe($main->id) - ->and(MakhzanFile::count())->toBe(1); // file survives on the live copy + ->and(StorelyFileLocation::count())->toBe(1) + ->and(StorelyFileLocation::first()->storely_space_id)->toBe($main->id) + ->and(StorelyFile::count())->toBe(1); // file survives on the live copy }); it('reports files with no copies and purges them only with purge', function () { makeLocalSpace('GcEmpty'); - $file = Makhzan\Facades\Makhzan::store(streamOf('lonely'), 'gc2.txt'); + $file = Storely\Facades\Storely::store(streamOf('lonely'), 'gc2.txt'); $file->locations()->forceDelete(); $result = app(GcService::class)->collect(); expect($result['empty_files'])->toBe(1) ->and($result['purged_files'])->toBe(0) - ->and(MakhzanFile::count())->toBe(1); + ->and(StorelyFile::count())->toBe(1); $purged = app(GcService::class)->collect(purge: true); expect($purged['purged_files'])->toBe(1) - ->and(MakhzanFile::count())->toBe(0); + ->and(StorelyFile::count())->toBe(0); }); it('dry run removes nothing', function () { $gone = makeLocalSpace('GcDry'); - $file = Makhzan\Facades\Makhzan::store(streamOf('dry'), 'gc3.txt'); + $file = Storely\Facades\Storely::store(streamOf('dry'), 'gc3.txt'); $gone->delete(); $result = app(GcService::class)->collect(dryRun: true); expect($result['dead_space_locations'])->toBe(1) - ->and(MakhzanFileLocation::withTrashed()->count())->toBe(1); + ->and(StorelyFileLocation::withTrashed()->count())->toBe(1); }); it('check-remote removes locations whose copy vanished and keeps unreachable ones', function () { makeLocalSpace('GcRemote'); - $file = Makhzan\Facades\Makhzan::store(streamOf('remote'), 'gc4.txt'); + $file = Storely\Facades\Storely::store(streamOf('remote'), 'gc4.txt'); $missing = gcWith(stubDriver(false))->collect(checkRemote: true); expect($missing['remote_missing_locations'])->toBe(1) ->and($file->locations()->count())->toBe(0); - $file2 = Makhzan\Facades\Makhzan::store(streamOf('still there'), 'gc5.txt'); + $file2 = Storely\Facades\Storely::store(streamOf('still there'), 'gc5.txt'); $present = gcWith(stubDriver(true))->collect(checkRemote: true); expect($present['remote_missing_locations'])->toBe(0) ->and($file2->locations()->count())->toBe(1); @@ -119,7 +119,7 @@ public function test(): string it('keeps rows when the space cannot be reached', function () { makeLocalSpace('GcDown'); - $file = Makhzan\Facades\Makhzan::store(streamOf('down'), 'gc6.txt'); + $file = Storely\Facades\Storely::store(streamOf('down'), 'gc6.txt'); $down = new class implements StorageDriver { @@ -137,7 +137,7 @@ public function delete(string $locator): void {} public function exists(string $locator): bool { - throw new MakhzanException('Reaching the space failed.'); + throw new StorelyException('Reaching the space failed.'); } public function test(): string @@ -153,10 +153,10 @@ public function test(): string it('runs through the artisan command', function () { makeLocalSpace('GcCmd'); - $file = Makhzan\Facades\Makhzan::store(streamOf('cmd'), 'gc7.txt'); + $file = Storely\Facades\Storely::store(streamOf('cmd'), 'gc7.txt'); $file->locations()->forceDelete(); - $this->artisan('makhzan:gc')->expectsOutputToContain('no copies left')->assertSuccessful(); - $this->artisan('makhzan:gc --purge')->assertSuccessful(); - expect(MakhzanFile::count())->toBe(0); + $this->artisan('storely:gc')->expectsOutputToContain('no copies left')->assertSuccessful(); + $this->artisan('storely:gc --purge')->assertSuccessful(); + expect(StorelyFile::count())->toBe(0); }); diff --git a/tests/Feature/RestoreReplicateTest.php b/tests/Feature/RestoreReplicateTest.php index 1781e10..cfd34e6 100644 --- a/tests/Feature/RestoreReplicateTest.php +++ b/tests/Feature/RestoreReplicateTest.php @@ -2,69 +2,69 @@ declare(strict_types=1); -use Makhzan\DriverFactory; -use Makhzan\Exceptions\MakhzanException; -use Makhzan\Models\MakhzanFile; -use Makhzan\Models\MakhzanFileLocation; +use Storely\DriverFactory; +use Storely\Exceptions\StorelyException; +use Storely\Models\StorelyFile; +use Storely\Models\StorelyFileLocation; it('restores a soft-deleted file whose copies are still in place', function () { makeLocalSpace('Restore'); - $file = Makhzan\Facades\Makhzan::store(streamOf('come back'), 'r1.txt'); - Makhzan\Facades\Makhzan::delete($file); + $file = Storely\Facades\Storely::store(streamOf('come back'), 'r1.txt'); + Storely\Facades\Storely::delete($file); expect($file->refresh()->trashed())->toBeTrue(); - $restored = Makhzan\Facades\Makhzan::restore($file); + $restored = Storely\Facades\Storely::restore($file); expect($restored->trashed())->toBeFalse() ->and($restored->locations()->count())->toBe(1); // the copy still serves the bytes - ['stream' => $stream] = Makhzan\Facades\Makhzan::read($restored); + ['stream' => $stream] = Storely\Facades\Storely::read($restored); expect(stream_get_contents($stream))->toBe('come back'); }); it('refuses to restore a file with no copies left', function () { makeLocalSpace('RestoreGone'); - $file = Makhzan\Facades\Makhzan::store(streamOf('gone'), 'r2.txt'); - Makhzan\Facades\Makhzan::delete($file); + $file = Storely\Facades\Storely::store(streamOf('gone'), 'r2.txt'); + Storely\Facades\Storely::delete($file); $file->locations()->forceDelete(); - Makhzan\Facades\Makhzan::restore($file->refresh()); -})->throws(MakhzanException::class, 'no copies left'); + Storely\Facades\Storely::restore($file->refresh()); +})->throws(StorelyException::class, 'no copies left'); it('restore on a live file is a no-op', function () { makeLocalSpace('RestoreLive'); - $file = Makhzan\Facades\Makhzan::store(streamOf('live'), 'r3.txt'); + $file = Storely\Facades\Storely::store(streamOf('live'), 'r3.txt'); - expect(Makhzan\Facades\Makhzan::restore($file)->trashed())->toBeFalse(); + expect(Storely\Facades\Storely::restore($file)->trashed())->toBeFalse(); }); it('replicates every file on a space to another space', function () { $from = makeLocalSpace('RepFrom'); $to = makeLocalSpace('RepTo', 200); - Makhzan\Facades\Makhzan::store(streamOf('one'), 'rep1.txt'); - Makhzan\Facades\Makhzan::store(streamOf('two'), 'rep2.txt'); + Storely\Facades\Storely::store(streamOf('one'), 'rep1.txt'); + Storely\Facades\Storely::store(streamOf('two'), 'rep2.txt'); - $this->artisan("makhzan:replicate {$from->id} {$to->id}") + $this->artisan("storely:replicate {$from->id} {$to->id}") ->expectsOutputToContain('Replicated 2 files') ->assertSuccessful(); - expect(MakhzanFileLocation::where('makhzan_space_id', $to->id)->count())->toBe(2); + expect(StorelyFileLocation::where('storely_space_id', $to->id)->count())->toBe(2); // the copies on the target serve the same bytes - $file = MakhzanFile::where('original_name', 'rep1.txt')->firstOrFail(); - $location = MakhzanFileLocation::where('makhzan_file_id', $file->id)->where('makhzan_space_id', $to->id)->firstOrFail(); + $file = StorelyFile::where('original_name', 'rep1.txt')->firstOrFail(); + $location = StorelyFileLocation::where('storely_file_id', $file->id)->where('storely_space_id', $to->id)->firstOrFail(); expect(stream_get_contents(app(DriverFactory::class)->make($to)->read($location->locator)))->toBe('one'); }); it('skips files already on the target and rejects a same-space run', function () { $from = makeLocalSpace('RepFrom2'); $to = makeLocalSpace('RepTo2', 200); - $file = Makhzan\Facades\Makhzan::store(streamOf('dup'), 'rep3.txt'); - Makhzan\Facades\Makhzan::files()->copyTo($file, $to); + $file = Storely\Facades\Storely::store(streamOf('dup'), 'rep3.txt'); + Storely\Facades\Storely::files()->copyTo($file, $to); - $this->artisan("makhzan:replicate {$from->id} {$to->id}") + $this->artisan("storely:replicate {$from->id} {$to->id}") ->expectsOutputToContain('Replicated 0 files') ->assertSuccessful(); - expect(MakhzanFileLocation::where('makhzan_space_id', $to->id)->count())->toBe(1); + expect(StorelyFileLocation::where('storely_space_id', $to->id)->count())->toBe(1); - $this->artisan("makhzan:replicate {$from->id} {$from->id}")->assertFailed(); - $this->artisan("makhzan:replicate {$from->id} 999")->assertFailed(); + $this->artisan("storely:replicate {$from->id} {$from->id}")->assertFailed(); + $this->artisan("storely:replicate {$from->id} 999")->assertFailed(); }); diff --git a/tests/Feature/RoutingRulesTest.php b/tests/Feature/RoutingRulesTest.php index 65da270..ccbd907 100644 --- a/tests/Feature/RoutingRulesTest.php +++ b/tests/Feature/RoutingRulesTest.php @@ -3,10 +3,10 @@ declare(strict_types=1); use Illuminate\Validation\ValidationException; -use Makhzan\Models\MakhzanRoutingRule; -use Makhzan\Services\FileStoreService; -use Makhzan\Services\RuleService; -use Makhzan\Services\SpaceService; +use Storely\Models\StorelyRoutingRule; +use Storely\Services\FileStoreService; +use Storely\Services\RuleService; +use Storely\Services\SpaceService; function storeCat(string $contents, string $category) { @@ -16,22 +16,22 @@ function storeCat(string $contents, string $category) it('routes a category to the rule space', function () { $default = makeLocalSpace('Default', 10); $images = makeLocalSpace('Images', 20); - app(RuleService::class)->create(['name' => 'Images rule', 'category' => 'image', 'makhzan_space_id' => $images->id]); + app(RuleService::class)->create(['name' => 'Images rule', 'category' => 'image', 'storely_space_id' => $images->id]); $file = storeCat('an-image', 'image'); - expect($file->locations()->first()->makhzan_space_id)->toBe($images->id); + expect($file->locations()->first()->storely_space_id)->toBe($images->id); $other = storeCat('a-doc', 'document'); - expect($other->locations()->first()->makhzan_space_id)->toBe($default->id); + expect($other->locations()->first()->storely_space_id)->toBe($default->id); }); it('honors rule size ranges', function () { $small = makeLocalSpace('Small', 10); $big = makeLocalSpace('Big', 20); - app(RuleService::class)->create(['name' => 'Big files', 'category' => 'any', 'min_size' => 100, 'makhzan_space_id' => $big->id]); + app(RuleService::class)->create(['name' => 'Big files', 'category' => 'any', 'min_size' => 100, 'storely_space_id' => $big->id]); - expect(storeCat(str_repeat('a', 50), 'general')->locations()->first()->makhzan_space_id)->toBe($small->id); - expect(storeCat(str_repeat('b', 150), 'general')->locations()->first()->makhzan_space_id)->toBe($big->id); + expect(storeCat(str_repeat('a', 50), 'general')->locations()->first()->storely_space_id)->toBe($small->id); + expect(storeCat(str_repeat('b', 150), 'general')->locations()->first()->storely_space_id)->toBe($big->id); }); it('evaluates rules by priority and falls through broken ones', function () { @@ -39,33 +39,33 @@ function storeCat(string $contents, string $category) $b = makeLocalSpace('RuleB', 60); $c = makeLocalSpace('RuleC', 70); $rules = app(RuleService::class); - $rules->create(['name' => 'to A', 'category' => 'x', 'priority' => 1, 'makhzan_space_id' => $a->id]); - $rules->create(['name' => 'to B', 'category' => 'x', 'priority' => 2, 'makhzan_space_id' => $b->id]); + $rules->create(['name' => 'to A', 'category' => 'x', 'priority' => 1, 'storely_space_id' => $a->id]); + $rules->create(['name' => 'to B', 'category' => 'x', 'priority' => 2, 'storely_space_id' => $b->id]); - expect(storeCat('one', 'x')->locations()->first()->makhzan_space_id)->toBe($a->id); + expect(storeCat('one', 'x')->locations()->first()->storely_space_id)->toBe($a->id); // Break A: credential change invalidates its check, so the rule falls through to B. app(SpaceService::class)->update($a, 'RuleA', ['root' => 'changed']); - expect(storeCat('two', 'x')->locations()->first()->makhzan_space_id)->toBe($b->id); + expect(storeCat('two', 'x')->locations()->first()->storely_space_id)->toBe($b->id); // Break B too: rules exhausted, plain fill order takes C. app(SpaceService::class)->update($b, 'RuleB', ['root' => 'changed']); - expect(storeCat('three', 'x')->locations()->first()->makhzan_space_id)->toBe($c->id); + expect(storeCat('three', 'x')->locations()->first()->storely_space_id)->toBe($c->id); }); it('ignores inactive rules and uses the rule mirror', function () { $main = makeLocalSpace('RuleMain', 10); $mirror = makeLocalSpace('RuleMirror', 20); $rules = app(RuleService::class); - $rule = $rules->create(['name' => 'mirrored', 'category' => 'vip', 'makhzan_space_id' => $main->id, 'mirror_space_id' => $mirror->id]); + $rule = $rules->create(['name' => 'mirrored', 'category' => 'vip', 'storely_space_id' => $main->id, 'mirror_space_id' => $mirror->id]); $file = storeCat('vip-bytes', 'vip'); expect($file->locations()->count())->toBe(2) - ->and($file->locations()->where('makhzan_space_id', $mirror->id)->first()->role->value)->toBe('mirror'); + ->and($file->locations()->where('storely_space_id', $mirror->id)->first()->role->value)->toBe('mirror'); $rules->update($rule, ['is_active' => false]); $file2 = storeCat('vip-bytes-2', 'vip'); - expect($file2->locations()->first()->makhzan_space_id)->toBe($main->id) // plain fill order + expect($file2->locations()->first()->storely_space_id)->toBe($main->id) // plain fill order ->and($file2->locations()->count())->toBe(1); // no space mirror set }); @@ -74,11 +74,11 @@ function storeCat(string $contents, string $category) $space = makeLocalSpace('VR', 10); $bad = [ - [['name' => 'x', 'makhzan_space_id' => $space->id], 'name'], - [['name' => 'ok', 'category' => 'not allowed!', 'makhzan_space_id' => $space->id], 'category'], - [['name' => 'ok', 'min_size' => 100, 'max_size' => 10, 'makhzan_space_id' => $space->id], 'max_size'], - [['name' => 'ok', 'makhzan_space_id' => 999999], 'makhzan_space_id'], - [['name' => 'ok', 'makhzan_space_id' => $space->id, 'mirror_space_id' => $space->id], 'mirror_space_id'], + [['name' => 'x', 'storely_space_id' => $space->id], 'name'], + [['name' => 'ok', 'category' => 'not allowed!', 'storely_space_id' => $space->id], 'category'], + [['name' => 'ok', 'min_size' => 100, 'max_size' => 10, 'storely_space_id' => $space->id], 'max_size'], + [['name' => 'ok', 'storely_space_id' => 999999], 'storely_space_id'], + [['name' => 'ok', 'storely_space_id' => $space->id, 'mirror_space_id' => $space->id], 'mirror_space_id'], ]; foreach ($bad as [$data, $key]) { try { @@ -93,14 +93,14 @@ function storeCat(string $contents, string $category) it('keeps existing values on partial update', function () { $space = makeLocalSpace('PU', 10); $rules = app(RuleService::class); - $rule = $rules->create(['name' => 'original', 'category' => 'docs', 'priority' => 5, 'makhzan_space_id' => $space->id]); + $rule = $rules->create(['name' => 'original', 'category' => 'docs', 'priority' => 5, 'storely_space_id' => $space->id]); $updated = $rules->update($rule, ['name' => 'renamed']); expect($updated->category)->toBe('docs') ->and($updated->priority)->toBe(5) - ->and($updated->makhzan_space_id)->toBe($space->id); + ->and($updated->storely_space_id)->toBe($space->id); $rules->delete($updated); - expect(MakhzanRoutingRule::find($rule->id))->toBeNull() - ->and(MakhzanRoutingRule::withTrashed()->find($rule->id))->not->toBeNull(); + expect(StorelyRoutingRule::find($rule->id))->toBeNull() + ->and(StorelyRoutingRule::withTrashed()->find($rule->id))->not->toBeNull(); }); diff --git a/tests/Feature/TemporaryUrlTest.php b/tests/Feature/TemporaryUrlTest.php index 678c345..29bc5de 100644 --- a/tests/Feature/TemporaryUrlTest.php +++ b/tests/Feature/TemporaryUrlTest.php @@ -3,16 +3,16 @@ declare(strict_types=1); use Illuminate\Contracts\Filesystem\Filesystem; -use Makhzan\Contracts\StorageDriver; -use Makhzan\Contracts\SupportsTemporaryUrls; -use Makhzan\DriverFactory; -use Makhzan\Drivers\FlysystemDriver; -use Makhzan\Exceptions\MakhzanException; -use Makhzan\Models\MakhzanFile; -use Makhzan\Models\MakhzanSpace; -use Makhzan\Services\FileStoreService; -use Makhzan\Services\SpaceResolver; -use Makhzan\Services\SpaceService; +use Storely\Contracts\StorageDriver; +use Storely\Contracts\SupportsTemporaryUrls; +use Storely\DriverFactory; +use Storely\Drivers\FlysystemDriver; +use Storely\Exceptions\StorelyException; +use Storely\Models\StorelyFile; +use Storely\Models\StorelySpace; +use Storely\Services\FileStoreService; +use Storely\Services\SpaceResolver; +use Storely\Services\SpaceService; it('delegates temporary urls to the disk', function () { $disk = Mockery::mock(Filesystem::class); @@ -22,24 +22,24 @@ expect($driver->temporaryUrl('docs/a.pdf', now()->addMinutes(5)))->toBe('https://signed.example/docs/a.pdf?sig=1'); }); -it('maps a disk without signing support to a makhzan exception', function () { +it('maps a disk without signing support to a storely exception', function () { $disk = Mockery::mock(Filesystem::class); $disk->shouldReceive('temporaryUrl')->andThrow(new RuntimeException('This driver does not support creating temporary URLs.')); $driver = new FlysystemDriver($disk); $driver->temporaryUrl('docs/a.pdf', now()->addMinutes(5)); -})->throws(MakhzanException::class, 'temporary URLs'); +})->throws(StorelyException::class, 'temporary URLs'); it('returns null when no space holding the file can sign', function () { makeLocalSpace('Plain'); - $file = Makhzan\Facades\Makhzan::store(streamOf('unsigned'), 'a.txt'); + $file = Storely\Facades\Storely::store(streamOf('unsigned'), 'a.txt'); - expect(Makhzan\Facades\Makhzan::temporaryUrl($file))->toBeNull(); + expect(Storely\Facades\Storely::temporaryUrl($file))->toBeNull(); }); it('signs from the first space whose driver supports it', function () { $space = makeLocalSpace('Signable'); - $file = Makhzan\Facades\Makhzan::store(streamOf('signed bytes'), 'b.txt'); + $file = Storely\Facades\Storely::store(streamOf('signed bytes'), 'b.txt'); $locator = $file->locations()->first()->locator; $fake = new class implements StorageDriver, SupportsTemporaryUrls @@ -81,7 +81,7 @@ public function temporaryUrl(string $locator, DateTimeInterface $expiresAt): str { public function __construct(private readonly StorageDriver $driver) {} - public function make(MakhzanSpace $space): StorageDriver + public function make(StorelySpace $space): StorageDriver { return $this->driver; } @@ -93,11 +93,11 @@ public function make(MakhzanSpace $space): StorageDriver expect($url)->toBe('https://signed.test/'.$locator) ->and($fake->calledWith)->not->toBeNull() ->and($fake->calledWith[1]->greaterThan(now()->addMinutes(9)))->toBeTrue(); - expect($space->id)->toBe($file->locations()->first()->makhzan_space_id); + expect($space->id)->toBe($file->locations()->first()->storely_space_id); }); it('clamps the expiry minutes', function () { - $file = new MakhzanFile; + $file = new StorelyFile; $service = app(FileStoreService::class); // no locations: null either way, but it must not throw on extreme values expect($service->temporaryUrl($file, 0))->toBeNull() diff --git a/tests/Pest.php b/tests/Pest.php index 8c41aec..ad4f423 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -2,6 +2,6 @@ declare(strict_types=1); -use Makhzan\Tests\TestCase; +use Storely\Tests\TestCase; uses(TestCase::class)->in('Unit', 'Feature'); diff --git a/tests/Support/helpers.php b/tests/Support/helpers.php index 72ff2f5..683a675 100644 --- a/tests/Support/helpers.php +++ b/tests/Support/helpers.php @@ -2,12 +2,12 @@ declare(strict_types=1); -use Makhzan\Enums\SpaceDriver; -use Makhzan\Enums\SpaceStatus; -use Makhzan\Models\MakhzanSpace; -use Makhzan\Services\SpaceService; +use Storely\Enums\SpaceDriver; +use Storely\Enums\SpaceStatus; +use Storely\Models\StorelySpace; +use Storely\Services\SpaceService; -function forcePassingCheck(MakhzanSpace $space): MakhzanSpace +function forcePassingCheck(StorelySpace $space): StorelySpace { $space->last_check_ok = true; $space->last_checked_at = now(); @@ -17,7 +17,7 @@ function forcePassingCheck(MakhzanSpace $space): MakhzanSpace return $space->refresh(); } -function makeLocalSpace(string $name = 'Space', int $priority = 100, ?int $capacity = null): MakhzanSpace +function makeLocalSpace(string $name = 'Space', int $priority = 100, ?int $capacity = null): StorelySpace { $spaces = app(SpaceService::class); $space = $spaces->create($name, SpaceDriver::Local, ['root' => preg_replace('/[^A-Za-z0-9_-]/', '', $name).bin2hex(random_bytes(3))], $priority, $capacity); diff --git a/tests/TestCase.php b/tests/TestCase.php index 853c878..bf11061 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,30 +2,30 @@ declare(strict_types=1); -namespace Makhzan\Tests; +namespace Storely\Tests; -use Makhzan\Facades\Makhzan; -use Makhzan\MakhzanServiceProvider; use Orchestra\Testbench\TestCase as Orchestra; +use Storely\Facades\Storely; +use Storely\StorelyServiceProvider; abstract class TestCase extends Orchestra { protected function getPackageProviders($app): array { - return [MakhzanServiceProvider::class]; + return [StorelyServiceProvider::class]; } protected function getPackageAliases($app): array { - return ['Makhzan' => Makhzan::class]; + return ['Storely' => Storely::class]; } protected function defineEnvironment($app): void { - $app['config']->set('app.key', 'base64:'.base64_encode(str_repeat('makhzan-test-key', 2))); + $app['config']->set('app.key', 'base64:'.base64_encode(str_repeat('storely-test-key', 2))); $app['config']->set('database.default', 'testing'); $app['config']->set('queue.default', 'sync'); - $app['config']->set('makhzan.local_root', 'framework/testing/makhzan'); + $app['config']->set('storely.local_root', 'framework/testing/storely'); } protected function defineDatabaseMigrations(): void diff --git a/tests/Unit/DriversTest.php b/tests/Unit/DriversTest.php index 4d93ada..6ff6317 100644 --- a/tests/Unit/DriversTest.php +++ b/tests/Unit/DriversTest.php @@ -4,23 +4,23 @@ use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Storage; -use Makhzan\DriverFactory; -use Makhzan\Drivers\FlysystemDriver; -use Makhzan\Drivers\GoogleDriveDriver; -use Makhzan\Drivers\TelegramDriver; -use Makhzan\Enums\SpaceDriver; -use Makhzan\Exceptions\MakhzanException; -use Makhzan\Services\SpaceService; +use Storely\DriverFactory; +use Storely\Drivers\FlysystemDriver; +use Storely\Drivers\GoogleDriveDriver; +use Storely\Drivers\TelegramDriver; +use Storely\Enums\SpaceDriver; +use Storely\Exceptions\StorelyException; +use Storely\Services\SpaceService; // ---------- FlysystemDriver ---------- it('round-trips a stream through flysystem', function () { $driver = new FlysystemDriver(Storage::build(['driver' => 'local', 'root' => storage_path('framework/testing/fly-'.bin2hex(random_bytes(4))), 'throw' => true])); - $locator = $driver->put('a/b/test.txt', streamOf('hello makhzan'), 'text/plain'); + $locator = $driver->put('a/b/test.txt', streamOf('hello storely'), 'text/plain'); expect($locator)->toBe('a/b/test.txt') ->and($driver->exists($locator))->toBeTrue() - ->and(stream_get_contents($driver->read($locator)))->toBe('hello makhzan'); + ->and(stream_get_contents($driver->read($locator)))->toBe('hello storely'); $driver->delete($locator); expect($driver->exists($locator))->toBeFalse(); @@ -36,7 +36,7 @@ $driver = new FlysystemDriver(Storage::build(['driver' => 'local', 'root' => storage_path('framework/testing/fly-'.bin2hex(random_bytes(4))), 'throw' => true])); $driver->read('nope/missing.txt'); -})->throws(MakhzanException::class); +})->throws(StorelyException::class); // ---------- TelegramDriver ---------- @@ -89,24 +89,24 @@ function telegramDriver(): TelegramDriver try { telegramDriver()->put('x.txt', streamOf('x')); - $this->fail('expected MakhzanException'); - } catch (MakhzanException $e) { + $this->fail('expected StorelyException'); + } catch (StorelyException $e) { expect($e->getMessage())->toContain('chat not found')->not->toContain('123:ABC'); } }); it('rejects malformed telegram locators', function () { telegramDriver()->read('not-a-locator'); -})->throws(MakhzanException::class); +})->throws(StorelyException::class); it('runs the telegram live test', function () { Http::fake([ - 'api.telegram.org/bot123:ABC/getMe' => Http::response(['ok' => true, 'result' => ['username' => 'makhzanbot']]), + 'api.telegram.org/bot123:ABC/getMe' => Http::response(['ok' => true, 'result' => ['username' => 'storelybot']]), 'api.telegram.org/bot123:ABC/sendDocument' => Http::response(['ok' => true, 'result' => ['message_id' => 5, 'document' => ['file_id' => 'F']]]), 'api.telegram.org/bot123:ABC/deleteMessage' => Http::response(['ok' => true, 'result' => true]), ]); - expect(telegramDriver()->test())->toContain('@makhzanbot'); + expect(telegramDriver()->test())->toContain('@storelybot'); }); it('checks telegram existence', function () { @@ -158,7 +158,7 @@ function fakeGdriveToken(): void ]); gdriveDriver()->exists('X'); - // exists() catches MakhzanException and returns false + // exists() catches StorelyException and returns false })->throwsNoExceptions(); it('returns false from exists() when drive errors', function () { @@ -173,9 +173,9 @@ function fakeGdriveToken(): void it('runs the google drive live test', function () { Http::fake([ 'oauth2.googleapis.com/token' => Http::response(['access_token' => 'ya29.token']), - 'www.googleapis.com/drive/v3/files/FOLDER1?fields=id,name' => Http::response(['id' => 'FOLDER1', 'name' => 'makhzan']), + 'www.googleapis.com/drive/v3/files/FOLDER1?fields=id,name' => Http::response(['id' => 'FOLDER1', 'name' => 'storely']), 'www.googleapis.com/upload/drive/v3/files*' => Http::response(['id' => 'TMPID']), - 'www.googleapis.com/drive/v3/files/TMPID?alt=media' => Http::response('makhzan-check'), + 'www.googleapis.com/drive/v3/files/TMPID?alt=media' => Http::response('storely-check'), 'www.googleapis.com/drive/v3/files/TMPID' => Http::response(null, 204), ]); diff --git a/tests/Unit/SpaceServiceTest.php b/tests/Unit/SpaceServiceTest.php index 915e481..018584e 100644 --- a/tests/Unit/SpaceServiceTest.php +++ b/tests/Unit/SpaceServiceTest.php @@ -4,11 +4,11 @@ use Illuminate\Support\Facades\DB; use Illuminate\Validation\ValidationException; -use Makhzan\Enums\SpaceDriver; -use Makhzan\Enums\SpaceStatus; -use Makhzan\Models\MakhzanFile; -use Makhzan\Models\MakhzanSpace; -use Makhzan\Services\SpaceService; +use Storely\Enums\SpaceDriver; +use Storely\Enums\SpaceStatus; +use Storely\Models\StorelyFile; +use Storely\Models\StorelySpace; +use Storely\Services\SpaceService; it('creates a disabled space with clamped priority and capacity', function () { $spaces = app(SpaceService::class); @@ -51,7 +51,7 @@ $spaces = app(SpaceService::class); $space = $spaces->create('Secrets', SpaceDriver::Local, ['root' => 'secrets-dir']); - $raw = DB::table('makhzan_spaces')->where('id', $space->id)->value('credentials'); + $raw = DB::table('storely_spaces')->where('id', $space->id)->value('credentials'); expect($raw)->not->toContain('secrets-dir') ->and($space->toArray())->not->toHaveKey('credentials') ->and($space->toArray())->not->toHaveKey('checked_config_hash') @@ -113,8 +113,8 @@ $space = $spaces->create('Disposable', SpaceDriver::Local, ['root' => 'disposable']); $spaces->delete($space); - expect(MakhzanSpace::find($space->id))->toBeNull() - ->and(MakhzanSpace::withTrashed()->find($space->id))->not->toBeNull(); + expect(StorelySpace::find($space->id))->toBeNull() + ->and(StorelySpace::withTrashed()->find($space->id))->not->toBeNull(); }); it('rejects oversized credential values', function () { @@ -123,7 +123,7 @@ })->throws(ValidationException::class); it('stores the original name safely', function () { - $file = new MakhzanFile; + $file = new StorelyFile; $file->sha256 = str_repeat('0', 64); $file->size = 1; $file->original_name = 'evil.php';