A free open source IT asset/license management system
Concurrency guard for asset checkin (mirrors checkout)
snipee788816c1098
diff --git a/app/Http/Controllers/Api/AssetsController.php b/app/Http/Controllers/Api/AssetsController.phpindex 9821475973..c2eddd58e7 100644--- a/app/Http/Controllers/Api/AssetsController.php+++ b/app/Http/Controllers/Api/AssetsController.php@@ -1484,77 +1484,100 @@ class AssetsController extends Controller$asset = Asset::with('model')->findOrFail($asset_id);$this->authorize('checkin', $asset);- $target = $asset->assignedTo;- if (is_null($target)) {- return response()->json(Helper::formatStandardApiResponse('error', [- 'asset_tag' => e($asset->asset_tag),- 'model' => e($asset->model->name),- 'model_number' => e($asset->model->model_number),- ], trans('admin/hardware/message.checkin.already_checked_in')));- }+ // Concurrency guard.+ $outcome = DB::transaction(function () use ($asset, $request): array {+ $locked = Asset::with(['model', 'licenseseats'])+ ->whereKey($asset->id)+ ->lockForUpdate()+ ->first();++ if (!$locked) {+ return ['status' => 'already_checked_in', 'asset' => $asset];+ }- $asset->expected_checkin = null;- // $asset->last_checkout = null;- $asset->last_checkin = now();- $asset->assignedTo()->disassociate($asset);- $asset->accepted = null;+ $target = $locked->assignedTo;+ if (is_null($target)) {+ return ['status' => 'already_checked_in', 'asset' => $locked];+ }- if ($request->input('clear_name') == '1') {- $asset->name = null;- } elseif ($request->has('name')) {- $asset->name = $request->input('name');- }+ $locked->expected_checkin = null;+ // $locked->last_checkout = null;+ $locked->last_checkin = now();+ $locked->assignedTo()->disassociate($locked);+ $locked->accepted = null;- $this->migrateLegacyLocations($asset);+ if ($request->input('clear_name') == '1') {+ $locked->name = null;+ } elseif ($request->has('name')) {+ $locked->name = $request->input('name');+ }- $asset->location_id = $asset->rtd_location_id;+ $this->migrateLegacyLocations($locked);- if ($request->filled('location_id')) {- $asset->location_id = $request->input('location_id');+ $locked->location_id = $locked->rtd_location_id;- if ($request->input('update_default_location')) {- $asset->rtd_location_id = $request->input('location_id');- }- }+ if ($request->filled('location_id')) {+ $locked->location_id = $request->input('location_id');- if ($request->filled('status_id')) {- $asset->status_id = $request->input('status_id');- }+ if ($request->input('update_default_location')) {+ $locked->rtd_location_id = $request->input('location_id');+ }+ }- $checkin_at = $request->filled('checkin_at') ? $request->input('checkin_at').' '.date('H:i:s') : date('Y-m-d H:i:s');- $originalValues = $asset->getRawOriginal();+ if ($request->filled('status_id')) {+ $locked->status_id = $request->input('status_id');+ }- if (($request->filled('checkin_at')) && ($request->input('checkin_at') != date('Y-m-d'))) {- $originalValues['action_date'] = $checkin_at;- }+ $checkin_at = $request->filled('checkin_at') ? $request->input('checkin_at') . ' ' . date('H:i:s') : date('Y-m-d H:i:s');+ $originalValues = $locked->getRawOriginal();- $asset->licenseseats->each(function (LicenseSeat $seat) {- $seat->update(['assigned_to' => null]);- });+ if (($request->filled('checkin_at')) && ($request->input('checkin_at') != date('Y-m-d'))) {+ $originalValues['action_date'] = $checkin_at;+ }- // Get all pending Acceptances for this asset and delete them- CheckoutAcceptance::pending()- ->whereHasMorph(- 'checkoutable',- [Asset::class],- function (Builder $query) use ($asset) {- $query->where('id', $asset->id);- }- )- ->get()- ->map(function ($acceptance) {- $acceptance->delete();+ $locked->licenseseats->each(function (LicenseSeat $seat) {+ $seat->update(['assigned_to' => null]);});- if ($asset->save()) {+ // Get all pending Acceptances for this asset and delete them+ CheckoutAcceptance::pending()+ ->whereHasMorph(+ 'checkoutable',+ [Asset::class],+ function (Builder $query) use ($locked) {+ $query->where('id', $locked->id);+ }+ )+ ->get()+ ->map(function ($acceptance) {+ $acceptance->delete();+ });++ if (!$locked->save()) {+ return ['status' => 'save_failed', 'asset' => $locked];+ }// Update the location of any child assetsAsset::where('assigned_type', Asset::class)- ->where('assigned_to', $asset->id)- ->update(['location_id' => $asset->location_id]);+ ->where('assigned_to', $locked->id)+ ->update(['location_id' => $locked->location_id]);- event(new CheckoutableCheckedIn($asset, $target, auth()->user(), $request->input('note'), $checkin_at, $originalValues));+ event(new CheckoutableCheckedIn($locked, $target, auth()->user(), $request->input('note'), $checkin_at, $originalValues));++ return ['status' => 'success', 'asset' => $locked];+ });++ $asset = $outcome['asset'];++ if ($outcome['status'] === 'already_checked_in') {+ return response()->json(Helper::formatStandardApiResponse('error', [+ 'asset_tag' => e($asset->asset_tag),+ 'model' => e($asset->model->name),+ 'model_number' => e($asset->model->model_number),+ ], trans('admin/hardware/message.checkin.already_checked_in')));+ }+ if ($outcome['status'] === 'success') {return response()->json(Helper::formatStandardApiResponse('success', ['asset_tag' => e($asset->asset_tag),'model' => e($asset->model->name),diff --git a/tests/Feature/Checkins/Api/AssetCheckinConcurrencyGuardTest.php b/tests/Feature/Checkins/Api/AssetCheckinConcurrencyGuardTest.phpnew file mode 100644index 0000000000..850c172643--- /dev/null+++ b/tests/Feature/Checkins/Api/AssetCheckinConcurrencyGuardTest.php@@ -0,0 +1,54 @@+<?php++namespace Tests\Feature\Checkins\Api;++use App\Events\CheckoutableCheckedIn;+use App\Models\Actionlog;+use App\Models\Asset;+use App\Models\User;+use Illuminate\Support\Facades\Event;+use Tests\TestCase;++class AssetCheckinConcurrencyGuardTest extends TestCase+{+ public function test_second_checkin_on_an_already_checked_in_asset_does_not_fire_event_or_log()+ {+ Event::fake([CheckoutableCheckedIn::class]);++ $assignedUser = User::factory()->create();+ $asset = Asset::factory()->assignedToUser($assignedUser)->create();++ $actor = User::factory()->checkinAssets()->create();++ $this->actingAsForApi($actor)+ ->postJson(route('api.asset.checkin', $asset))+ ->assertStatusMessageIs('success');++ Event::assertDispatchedTimes(CheckoutableCheckedIn::class, 1);+ $logsAfterFirstCheckin = Actionlog::query()+ ->where('item_type', Asset::class)+ ->where('item_id', $asset->id)+ ->count();++ // Second request against the now-checked-in asset must bail out+ // on the re-checked null target. Pre-fix the unlocked initial read+ // could still observe the asset as checked out mid-race and emit+ // a duplicate event + a duplicate log row.+ $this->actingAsForApi($actor)+ ->postJson(route('api.asset.checkin', $asset))+ ->assertStatusMessageIs('error');++ Event::assertDispatchedTimes(CheckoutableCheckedIn::class, 1);++ $logsAfterSecondCheckin = Actionlog::query()+ ->where('item_type', Asset::class)+ ->where('item_id', $asset->id)+ ->count();++ $this->assertSame(+ $logsAfterFirstCheckin,+ $logsAfterSecondCheckin,+ 'A second checkin against an already-checked-in asset must not create another action-log row.'+ );+ }+}