Enha: tx for cron
This commit is contained in:
		| @@ -29,18 +29,36 @@ func (cm *CronManager) Start() { | ||||
| } | ||||
|  | ||||
| func (cm *CronManager) CleanupRooms() { | ||||
| 	ctx := context.Background() | ||||
| 	ctx, tx, err := cm.repo.InitTx(context.Background()) | ||||
| 	if err != nil { | ||||
| 		cm.log.Error("failed to init transaction", "err", err) | ||||
| 		return | ||||
| 	} | ||||
| 	defer func() { | ||||
| 		if r := recover(); r != nil { | ||||
| 			if err := tx.Rollback(); err != nil { | ||||
| 				cm.log.Error("failed to rollback transaction", "err", err) | ||||
| 			} | ||||
| 			panic(r) | ||||
| 		} | ||||
| 	}() | ||||
|  | ||||
| 	rooms, err := cm.repo.RoomList(ctx) | ||||
| 	if err != nil { | ||||
| 		cm.log.Error("failed to get rooms list", "err", err) | ||||
| 		if err := tx.Rollback(); err != nil { | ||||
| 			cm.log.Error("failed to rollback transaction", "err", err) | ||||
| 		} | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	for _, room := range rooms { | ||||
| 		players, err := cm.repo.PlayerListByRoom(ctx, room.ID) | ||||
| 		if err != nil { | ||||
| 			cm.log.Error("failed to get players for room", "room_id", room.ID, "err", err) | ||||
| 			continue | ||||
| 		} | ||||
|  | ||||
| 		if len(players) == 0 { | ||||
| 			cm.log.Info("deleting empty room", "room_id", room.ID) | ||||
| 			if err := cm.repo.RoomDeleteByID(ctx, room.ID); err != nil { | ||||
| @@ -48,6 +66,7 @@ func (cm *CronManager) CleanupRooms() { | ||||
| 			} | ||||
| 			continue | ||||
| 		} | ||||
|  | ||||
| 		creatorInRoom := false | ||||
| 		for _, player := range players { | ||||
| 			if player.Username == room.CreatorName { | ||||
| @@ -55,6 +74,7 @@ func (cm *CronManager) CleanupRooms() { | ||||
| 				break | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		if !creatorInRoom { | ||||
| 			cm.log.Info("deleting room because creator left", "room_id", room.ID) | ||||
| 			for _, player := range players { | ||||
| @@ -73,4 +93,9 @@ func (cm *CronManager) CleanupRooms() { | ||||
| 			} | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	if err := tx.Commit(); err != nil { | ||||
| 		cm.log.Error("failed to commit transaction", "err", err) | ||||
| 	} | ||||
| } | ||||
|  | ||||
|   | ||||
		Reference in New Issue
	
	Block a user
	 Grail Finder
					Grail Finder