|
| 1 | +# Copyright 2025 The Marin Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""File-based queue implementation for cross-subprocess communication. |
| 16 | +
|
| 17 | +This queue implementation uses the filesystem for state management, enabling |
| 18 | +reliable cross-process communication even when using subprocess.Popen (which |
| 19 | +doesn't share memory like multiprocessing.Process does). |
| 20 | +""" |
| 21 | + |
| 22 | +import json |
| 23 | +import time |
| 24 | +import uuid |
| 25 | +from pathlib import Path |
| 26 | +from typing import Any |
| 27 | + |
| 28 | +from fray.cluster.queue import Lease |
| 29 | + |
| 30 | + |
| 31 | +class FileQueue: |
| 32 | + """File-based queue implementation for cross-subprocess communication. |
| 33 | +
|
| 34 | + Uses the filesystem to store queue state, allowing multiple independent |
| 35 | + processes (even those started via subprocess.Popen) to share a queue. |
| 36 | +
|
| 37 | + Queue structure: |
| 38 | + - {queue_dir}/available/{uuid}.json - available tasks |
| 39 | + - {queue_dir}/leased/{uuid}.json - currently leased tasks |
| 40 | + - {queue_dir}/.lock - simple file-based lock (not perfect but good enough) |
| 41 | + """ |
| 42 | + |
| 43 | + def __init__(self, name: str, queue_dir: Path | None = None): |
| 44 | + """Initialize a file-based queue. |
| 45 | +
|
| 46 | + Args: |
| 47 | + name: Unique queue name |
| 48 | + queue_dir: Directory to store queue files (default: /tmp/fray_queues) |
| 49 | + """ |
| 50 | + if queue_dir is None: |
| 51 | + queue_dir = Path("/tmp/fray_queues") |
| 52 | + |
| 53 | + self._name = name |
| 54 | + self._base_dir = queue_dir / name |
| 55 | + self._available_dir = self._base_dir / "available" |
| 56 | + self._leased_dir = self._base_dir / "leased" |
| 57 | + |
| 58 | + # Create directories |
| 59 | + self._available_dir.mkdir(parents=True, exist_ok=True) |
| 60 | + self._leased_dir.mkdir(parents=True, exist_ok=True) |
| 61 | + |
| 62 | + def push(self, item: Any) -> None: |
| 63 | + """Add an item to the queue.""" |
| 64 | + item_id = str(uuid.uuid4()) |
| 65 | + file_path = self._available_dir / f"{item_id}.json" |
| 66 | + |
| 67 | + with open(file_path, "w") as f: |
| 68 | + json.dump({"item": item, "timestamp": time.time()}, f) |
| 69 | + |
| 70 | + def peek(self) -> Any | None: |
| 71 | + """View the next available item without acquiring a lease.""" |
| 72 | + files = sorted(self._available_dir.glob("*.json")) |
| 73 | + if not files: |
| 74 | + return None |
| 75 | + |
| 76 | + with open(files[0]) as f: |
| 77 | + data = json.load(f) |
| 78 | + return data["item"] |
| 79 | + |
| 80 | + def pop(self) -> Lease[Any] | None: |
| 81 | + """Acquire a lease on the next available item. |
| 82 | +
|
| 83 | + Also checks for expired leases (older than 60 seconds) and requeues them. |
| 84 | + """ |
| 85 | + # Check for expired leases and requeue them |
| 86 | + current_time = time.time() |
| 87 | + lease_timeout = 60.0 # seconds |
| 88 | + |
| 89 | + for leased_file in self._leased_dir.glob("*.json"): |
| 90 | + try: |
| 91 | + with open(leased_file) as f: |
| 92 | + data = json.load(f) |
| 93 | + |
| 94 | + # Check if lease has expired |
| 95 | + lease_time = data.get("lease_time", 0) |
| 96 | + if current_time - lease_time > lease_timeout: |
| 97 | + # Requeue expired lease |
| 98 | + available_path = self._available_dir / leased_file.name |
| 99 | + leased_file.rename(available_path) |
| 100 | + except (FileNotFoundError, json.JSONDecodeError): |
| 101 | + # File was removed or corrupted, skip |
| 102 | + continue |
| 103 | + |
| 104 | + # Find oldest available item |
| 105 | + files = sorted(self._available_dir.glob("*.json")) |
| 106 | + if not files: |
| 107 | + return None |
| 108 | + |
| 109 | + # Try to move file to leased directory (atomic operation) |
| 110 | + for file_path in files: |
| 111 | + lease_id = file_path.stem |
| 112 | + leased_path = self._leased_dir / f"{lease_id}.json" |
| 113 | + |
| 114 | + try: |
| 115 | + # Read the item first |
| 116 | + with open(file_path) as f: |
| 117 | + data = json.load(f) |
| 118 | + |
| 119 | + # Add lease time |
| 120 | + data["lease_time"] = time.time() |
| 121 | + |
| 122 | + # Write with lease time, then rename (atomic) |
| 123 | + temp_path = file_path.with_suffix(".tmp") |
| 124 | + with open(temp_path, "w") as f: |
| 125 | + json.dump(data, f) |
| 126 | + |
| 127 | + temp_path.rename(file_path) |
| 128 | + file_path.rename(leased_path) |
| 129 | + |
| 130 | + return Lease( |
| 131 | + item=data["item"], |
| 132 | + lease_id=lease_id, |
| 133 | + timestamp=data["lease_time"], |
| 134 | + ) |
| 135 | + except FileNotFoundError: |
| 136 | + # Another process got it first, try next file |
| 137 | + continue |
| 138 | + |
| 139 | + return None |
| 140 | + |
| 141 | + def done(self, lease: Lease[Any]) -> None: |
| 142 | + """Mark a leased task as successfully completed.""" |
| 143 | + leased_path = self._leased_dir / f"{lease.lease_id}.json" |
| 144 | + |
| 145 | + if not leased_path.exists(): |
| 146 | + raise ValueError(f"Invalid lease: {lease.lease_id}") |
| 147 | + |
| 148 | + leased_path.unlink() |
| 149 | + |
| 150 | + def release(self, lease: Lease[Any]) -> None: |
| 151 | + """Release a lease and requeue the item.""" |
| 152 | + leased_path = self._leased_dir / f"{lease.lease_id}.json" |
| 153 | + |
| 154 | + if not leased_path.exists(): |
| 155 | + raise ValueError(f"Invalid lease: {lease.lease_id}") |
| 156 | + |
| 157 | + # Move back to available |
| 158 | + available_path = self._available_dir / f"{lease.lease_id}.json" |
| 159 | + leased_path.rename(available_path) |
| 160 | + |
| 161 | + def size(self) -> int: |
| 162 | + """Return the total number of items in the queue.""" |
| 163 | + available = len(list(self._available_dir.glob("*.json"))) |
| 164 | + leased = len(list(self._leased_dir.glob("*.json"))) |
| 165 | + return available + leased |
| 166 | + |
| 167 | + def pending(self) -> int: |
| 168 | + """Return the number of items available for leasing.""" |
| 169 | + return len(list(self._available_dir.glob("*.json"))) |
0 commit comments