Search by

elbanbydev / makhzan

elbanbydev

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, mirror

Package info

github.com/elbanbydev/storely

pkg:composer/elbanbydev/makhzan

Statistics

Installs: 3

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

v0.7.0 2026-12-04 21:07 UTC

This package is auto-updated.

Last update: 2026-12-04 21:13:05 UTC


README

CI Latest release PHP License

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).

التوثيق بالعربية

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.

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. 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 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, 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 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 — 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

  • PHP 8.2+, Laravel 11 or 12
  • league/flysystem-aws-s3-v3 for S3-compatible spaces (R2, B2, S3): composer require league/flysystem-aws-s3-v3

Install

composer require elbanbydev/storely
php artisan migrate

Optionally publish the config:

php artisan vendor:publish --tag=storely-config

Quick start

use Storely\Enums\SpaceDriver;
use Storely\Facades\Storely;

// 1. Register a space. Credentials are encrypted at rest and never returned.
$r2 = Storely::addSpace('R2 main', SpaceDriver::R2, [
    'account_id' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'bucket' => 'my-bucket',
    'access_key' => '...',
    'secret_key' => '...',
], priority: 10, capacityBytes: 10 * 1024 ** 3);

// 2. Run the live check, then activate. Activation without a passing check is refused.
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 = Storely::store($stream, 'lecture.pdf', 'application/pdf');
$contents = stream_get_contents(Storely::read($file)['stream']);

// 4. See usage per space.
foreach (Storely::usage() as $spaceId => $u) {
    // $u = ['files' => 12, 'bytes' => 458752, 'percent' => 4, 'warning' => false]
}

Concepts

Spaces and statuses

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
active yes yes
read_only yes no
draining yes no (a background drain is emptying it)
disabled no no

A space can only leave disabled after check() passes on its exact current credentials (a SHA-256 fingerprint is stored; editing credentials invalidates it and disables the space).

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, 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. Storely::store() takes a category (default general):

Storely::store($stream, 'invoice.pdf', 'application/pdf', 'invoices');

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
    '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 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:

$url = Storely::temporaryUrl($file, 10); // valid 10 minutes, null when no copy can sign

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

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):

php artisan storely:replicate 1 2     # from space 1 to space 2
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. storely:gc cleans those rows:

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 storely:verify to refresh verified_at on copies that do exist.

Health checks

Storely::health()->check($space);   // one space
Storely::health()->checkAll();      // every space
Storely::health()->unhealthy();     // serving spaces whose check no longer matches
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

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):

Schedule::command('storely:health')->hourly();

A failing check disables the space (writes skip it immediately) and fires SpaceChecked.

Capacity warnings

Set capacity_bytes on a space and listen:

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 (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:

Storely::spaces()->setMirror($main, $backup);

Draining a space

To retire a space, empty it into another one in the background:

$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.

Events

FileStored · SpaceFailover · SpaceChecked · SpaceCapacityWarning · MoveCompleted

Drivers

Driver SpaceDriver Credentials Locator
Local disk (dev/tests) Local root object key
Cloudflare R2 R2 account_id, bucket, access_key, secret_key object key
Backblaze B2 B2 endpoint, region, bucket, access_key, secret_key object key
S3-compatible S3 same as B2 object key
Google Drive GoogleDrive client_id, client_secret, refresh_token, folder_id Drive file id
Telegram Bot Telegram bot_token, chat_id, proxy_base_url (optional) <message_id>:<file_id>

Each driver's fields() describes its credential fields (label, secret, required) and guide() gives setup steps — use them to build an admin form. Telegram uploads are capped at 20 MB; set proxy_base_url (e.g. a Cloudflare Worker) so reads don't burn your server's bandwidth.

Security model

  • 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/storely.
  • Stored file names are reduced to a safe basename.
  • 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 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

composer check   # pint --test, phpstan (level 8), pest

Credits

Built by Ahmed Elbanby with Instinct, extracted from the storage system of the Lakhas platform.

License

MIT — see LICENSE.md.