Alaea 2.7.0__tar.gz → 2.7.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. alaea-2.7.2/.VERSION +1 -0
  2. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Blogging.py +214 -77
  3. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Standard/xr_attrs.py +13 -7
  4. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Standard/xr_netcdf.py +31 -18
  5. {alaea-2.7.0 → alaea-2.7.2}/Alaea/netcdf_input.py +78 -45
  6. {alaea-2.7.0 → alaea-2.7.2}/Alaea/storage.py +20 -2
  7. {alaea-2.7.0 → alaea-2.7.2/Alaea.egg-info}/PKG-INFO +2 -1
  8. {alaea-2.7.0 → alaea-2.7.2}/Alaea.egg-info/SOURCES.txt +5 -1
  9. {alaea-2.7.0 → alaea-2.7.2}/Alaea.egg-info/requires.txt +1 -0
  10. {alaea-2.7.0 → alaea-2.7.2}/ChangeLog.md +25 -0
  11. {alaea-2.7.0/Alaea.egg-info → alaea-2.7.2}/PKG-INFO +2 -1
  12. {alaea-2.7.0 → alaea-2.7.2}/setup.py +2 -1
  13. {alaea-2.7.0 → alaea-2.7.2}/tests/test_core.py +78 -9
  14. alaea-2.7.2/tests/test_logging_background.py +171 -0
  15. {alaea-2.7.0 → alaea-2.7.2}/tests/test_logging_multiprocess.py +8 -5
  16. alaea-2.7.2/tests/test_logging_recovery.py +87 -0
  17. alaea-2.7.2/tests/test_logging_retention.py +87 -0
  18. alaea-2.7.2/tests/test_netcdf_failures.py +234 -0
  19. alaea-2.7.0/.VERSION +0 -1
  20. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Pyshell/RS_File.py +0 -0
  21. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Pyshell/__init__.py +0 -0
  22. {alaea-2.7.0 → alaea-2.7.2}/Alaea/S_DateTime.py +0 -0
  23. {alaea-2.7.0 → alaea-2.7.2}/Alaea/SameAsMATLAB/CoorTrans.py +0 -0
  24. {alaea-2.7.0 → alaea-2.7.2}/Alaea/SameAsMATLAB/__init__.py +0 -0
  25. {alaea-2.7.0 → alaea-2.7.2}/Alaea/SameAsMATLAB/calculatefuns.py +0 -0
  26. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Standard/__init__.py +0 -0
  27. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Standard/vars_name.py +0 -0
  28. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Standard/xr_atmos.py +0 -0
  29. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Standard/xr_ice.py +0 -0
  30. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Standard/xr_vars.py +0 -0
  31. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Standard/xr_wave.py +0 -0
  32. {alaea-2.7.0 → alaea-2.7.2}/Alaea/Standard/xr_wind.py +0 -0
  33. {alaea-2.7.0 → alaea-2.7.2}/Alaea/__init__.py +0 -0
  34. {alaea-2.7.0 → alaea-2.7.2}/Alaea/baysalt/Forage/__init__.py +0 -0
  35. {alaea-2.7.0 → alaea-2.7.2}/Alaea/baysalt/Forage/erosion_data/__init__.py +0 -0
  36. {alaea-2.7.0 → alaea-2.7.2}/Alaea/baysalt/__init__.py +0 -0
  37. {alaea-2.7.0 → alaea-2.7.2}/Alaea/baysalt/erosion_coastline.py +0 -0
  38. {alaea-2.7.0 → alaea-2.7.2}/Alaea/commonCode.py +0 -0
  39. {alaea-2.7.0 → alaea-2.7.2}/Alaea/cprintfs.py +0 -0
  40. {alaea-2.7.0 → alaea-2.7.2}/Alaea/exutils/Interp/Interp_g2s.py +0 -0
  41. {alaea-2.7.0 → alaea-2.7.2}/Alaea/exutils/Interp/Interp_s2g.py +0 -0
  42. {alaea-2.7.0 → alaea-2.7.2}/Alaea/exutils/Interp/__init__.py +0 -0
  43. {alaea-2.7.0 → alaea-2.7.2}/Alaea/exutils/Interp/interpolate.py +0 -0
  44. {alaea-2.7.0 → alaea-2.7.2}/Alaea/exutils/__init__.py +0 -0
  45. {alaea-2.7.0 → alaea-2.7.2}/Alaea/pFVCOM/__init__.py +0 -0
  46. {alaea-2.7.0 → alaea-2.7.2}/Alaea/pFVCOM/fvcom_class.py +0 -0
  47. {alaea-2.7.0 → alaea-2.7.2}/Alaea/pFVCOM/fvcom_image.py +0 -0
  48. {alaea-2.7.0 → alaea-2.7.2}/Alaea/pFVCOM/fvcom_load.py +0 -0
  49. {alaea-2.7.0 → alaea-2.7.2}/Alaea/pFVCOM/fvcom_tools.py +0 -0
  50. {alaea-2.7.0 → alaea-2.7.2}/Alaea/pFVCOM/writeFile.py +0 -0
  51. {alaea-2.7.0 → alaea-2.7.2}/Alaea/processBar.py +0 -0
  52. {alaea-2.7.0 → alaea-2.7.2}/Alaea/read_conf.py +0 -0
  53. {alaea-2.7.0 → alaea-2.7.2}/Alaea/server_info.py +0 -0
  54. {alaea-2.7.0 → alaea-2.7.2}/Alaea/tools/P_params.py +0 -0
  55. {alaea-2.7.0 → alaea-2.7.2}/Alaea/tools/Read.py +0 -0
  56. {alaea-2.7.0 → alaea-2.7.2}/Alaea/tools/__init__.py +0 -0
  57. {alaea-2.7.0 → alaea-2.7.2}/Alaea/tools/download_check.py +0 -0
  58. {alaea-2.7.0 → alaea-2.7.2}/Alaea/tools/geo_distance.py +0 -0
  59. {alaea-2.7.0 → alaea-2.7.2}/Alaea/tools/kml2shp.py +0 -0
  60. {alaea-2.7.0 → alaea-2.7.2}/Alaea/warningTools/__init__.py +0 -0
  61. {alaea-2.7.0 → alaea-2.7.2}/Alaea.egg-info/dependency_links.txt +0 -0
  62. {alaea-2.7.0 → alaea-2.7.2}/Alaea.egg-info/top_level.txt +0 -0
  63. {alaea-2.7.0 → alaea-2.7.2}/LICENSE +0 -0
  64. {alaea-2.7.0 → alaea-2.7.2}/MANIFEST.in +0 -0
  65. {alaea-2.7.0 → alaea-2.7.2}/README.md +0 -0
  66. {alaea-2.7.0 → alaea-2.7.2}/pyproject.toml +0 -0
  67. {alaea-2.7.0 → alaea-2.7.2}/setup.cfg +0 -0
  68. {alaea-2.7.0 → alaea-2.7.2}/tests/test_atmos_weather.py +0 -0
  69. {alaea-2.7.0 → alaea-2.7.2}/tests/test_cumulative_maximum.py +0 -0
  70. {alaea-2.7.0 → alaea-2.7.2}/tests/test_erosion_dataarray.py +0 -0
alaea-2.7.2/.VERSION ADDED
@@ -0,0 +1 @@
1
+ v2.7.2
@@ -17,7 +17,9 @@ import hashlib
17
17
  import logging
18
18
  import os
19
19
  import shutil
20
+ import tempfile
20
21
  import time
22
+ from concurrent.futures import ThreadPoolExecutor
21
23
  from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
22
24
  from pathlib import Path
23
25
  from typing import TYPE_CHECKING, Any, Literal, Optional, cast
@@ -50,7 +52,7 @@ try:
50
52
  except ImportError:
51
53
  zstandard = None
52
54
 
53
- from .commonCode import UTC, rmfiles, whether_instanced
55
+ from .commonCode import rmfiles, whether_instanced
54
56
 
55
57
  __all__ = ['Blog', 'test', 'debug', 'info', 'warning', 'error', 'critical', 'exception', 'log']
56
58
 
@@ -76,8 +78,70 @@ def _get_default_blog() -> "Blog":
76
78
 
77
79
 
78
80
  def _local_converter(timestamp):
79
- """把 UTC 时间戳显式转换为运行环境本地时区的 ``struct_time``。"""
80
- return datetime.datetime.fromtimestamp(timestamp, UTC).astimezone().timetuple()
81
+ """将 UTC 时间戳转换为保留时区名称和偏移的本地时间。
82
+
83
+ Args:
84
+ timestamp (float): 自 Unix epoch 起的 UTC 秒数。
85
+
86
+ Returns:
87
+ time.struct_time: 本地时间及其 tm_zone、tm_gmtoff 字段。
88
+
89
+ Raises:
90
+ OverflowError: 时间戳超出平台支持范围。
91
+ """
92
+ return time.localtime(timestamp)
93
+
94
+
95
+ def _compress_rotated_log(source, destination, opener, handler=None):
96
+ """压缩已隔离日志,发布时核对原归档身份并保留其时间顺序。
97
+
98
+ Args:
99
+ source (str): 完整原始归档;同步大小轮转时由调用方持有目录锁。
100
+ destination (str): 完成后的压缩归档路径。
101
+ opener (Callable): gzip.open或zstandard.open。
102
+ handler (_ProcessSafeTimedRotatingFileHandler | None): 后台模式发布时短暂取得目录锁。
103
+
104
+ Returns:
105
+ None。归档已被保留规则删除时丢弃压缩结果。
106
+
107
+ Raises:
108
+ OSError: 读取、压缩或发布失败,原始归档仍可读取。
109
+ """
110
+ temporary = None
111
+ try:
112
+ try:
113
+ source_stream = open(source, 'rb')
114
+ except FileNotFoundError:
115
+ if handler is not None:
116
+ return
117
+ raise
118
+ with source_stream:
119
+ source_stat = os.fstat(source_stream.fileno())
120
+ descriptor, temporary = tempfile.mkstemp(prefix=f'{Path(source).name}.alaea-compress-{os.getpid()}-', suffix='.tmp', dir=Path(source).parent)
121
+ os.close(descriptor)
122
+ with opener(temporary, 'wb') as target_stream:
123
+ shutil.copyfileobj(source_stream, target_stream)
124
+ lock_token = handler._acquire_process_lock() if handler is not None else None
125
+ try:
126
+ try:
127
+ current_stat = os.stat(source, follow_symlinks=False)
128
+ except FileNotFoundError:
129
+ if handler is not None:
130
+ return
131
+ raise
132
+ if (current_stat.st_dev, current_stat.st_ino, current_stat.st_size, current_stat.st_mtime_ns) != (source_stat.st_dev, source_stat.st_ino, source_stat.st_size, source_stat.st_mtime_ns):
133
+ raise OSError(f'压缩期间原始日志归档变化:{source}')
134
+ os.chmod(temporary, source_stat.st_mode & 0o777)
135
+ os.utime(temporary, ns=(source_stat.st_atime_ns, source_stat.st_mtime_ns))
136
+ os.replace(temporary, destination)
137
+ temporary = None
138
+ os.remove(source)
139
+ finally:
140
+ if lock_token is not None:
141
+ handler._release_process_lock(lock_token)
142
+ finally:
143
+ if temporary is not None:
144
+ os.remove(temporary)
81
145
 
82
146
 
83
147
  class _ProcessSafeRotatingMixin:
@@ -155,23 +219,26 @@ class _ProcessSafeRotatingMixin:
155
219
  _windows_kernel32.CloseHandle(handle)
156
220
 
157
221
  def _reopen_replaced_stream(self):
158
- """其他进程替换当前日志文件后,重新打开日志流。
222
+ """其他进程替换或移走当前日志文件后,重新打开日志流。
159
223
 
160
224
  Returns:
161
225
  None。
162
226
 
163
227
  Raises:
164
- 不额外抛出异常;无法读取文件元数据时继续使用现有日志流。
228
+ OSError: 当前路径已变化但无法重新打开日志流。
165
229
  """
166
230
  if self.stream is None:
167
231
  return
168
232
  try:
169
233
  stream_stat = os.fstat(self.stream.fileno())
170
234
  path_stat = os.stat(self.baseFilename)
235
+ if (stream_stat.st_dev, stream_stat.st_ino) == (path_stat.st_dev, path_stat.st_ino):
236
+ return
237
+ except FileNotFoundError:
238
+ # 轮转进程可能在隔离旧文件后退出,不能继续向已归档或已删除的 inode 写入。
239
+ pass
171
240
  except OSError:
172
241
  return
173
- if (stream_stat.st_dev, stream_stat.st_ino) == (path_stat.st_dev, path_stat.st_ino):
174
- return
175
242
  self.stream.close()
176
243
  self.stream = self._open()
177
244
 
@@ -243,75 +310,121 @@ class _ProcessSafeRotatingFileHandler(_ProcessSafeRotatingMixin, RotatingFileHan
243
310
  class _ProcessSafeTimedRotatingFileHandler(_ProcessSafeRotatingMixin, TimedRotatingFileHandler):
244
311
  """受跨进程锁保护的按时间轮转 handler。"""
245
312
 
313
+ def __init__(self, *args, **kwargs):
314
+ """初始化惰性压缩线程。
246
315
 
247
- class _SizeAndTimeRotatingFileHandler(_ProcessSafeRotatingMixin, TimedRotatingFileHandler):
248
- """在时间或文件大小任一条件满足时轮转日志。"""
316
+ Args:
317
+ args (tuple): 标准TimedRotatingFileHandler位置参数。
318
+ kwargs (dict): 标准处理器关键字参数。
249
319
 
250
- def __init__(self, filename, maxBytes, when, interval, backupCount, encoding='utf-8', delay=True, utc=False):
251
- """初始化组合轮转处理器。
320
+ Returns:
321
+ None。
322
+ """
323
+ self.compression_opener = None
324
+ self._compression_executor = None
325
+ self._compression_pid = os.getpid()
326
+ super().__init__(*args, **kwargs)
327
+
328
+ def rotation_filename(self, default_name):
329
+ """按原始及已压缩归档共同避让同周期名称。
252
330
 
253
331
  Args:
254
- filename: 当前日志文件路径。
255
- maxBytes: 触发轮转的最大字节数;零表示不按大小触发。
256
- when: 按时间轮转使用的时间单位。
257
- interval: 时间轮转间隔数量。
258
- backupCount: 保留的历史文件数量。
259
- encoding: 日志文件编码。
260
- delay: 是否延迟到首次写入时打开文件。
261
- utc: 是否使用 UTC 计算轮转时间。
332
+ default_name (str): 标准处理器生成的时间归档名。
262
333
 
263
334
  Returns:
264
- None.
265
-
266
- Raises:
267
- ValueError: 时间轮转参数无效时抛出。
268
- OSError: 无法检查或打开日志文件时抛出。
335
+ str。必要时在压缩后缀前增加数字序号。
269
336
  """
270
- super().__init__(filename, when=when, interval=interval, backupCount=backupCount, encoding=encoding,
271
- delay=delay, utc=utc, atTime=datetime.time(0, 0, 0))
272
- self.maxBytes = maxBytes
337
+ candidate = super().rotation_filename(default_name)
338
+ extension = next((suffix for suffix in ('.zst', '.gz') if candidate.endswith(suffix)), '')
339
+ stem = candidate[:-len(extension)] if extension else candidate
340
+ sequence = 0
341
+ while any(os.path.lexists(f'{stem}{suffix}') for suffix in ('', '.gz', '.zst')):
342
+ sequence += 1
343
+ stem = f'{default_name}.{sequence}'
344
+ return f'{stem}{extension}'
273
345
 
274
- def shouldRollover(self, record):
275
- """判断写入当前记录前是否需要轮转。
346
+ def rotate(self, source, destination):
347
+ """时间轮转在目录锁内隔离旧日志,压缩在后台执行。
276
348
 
277
349
  Args:
278
- record: 即将写入的日志记录。
350
+ source (str): 当前日志文件。
351
+ destination (str): 时间归档目标,压缩后缀由既有namer生成。
279
352
 
280
353
  Returns:
281
- 时间或大小条件任一满足时返回 ``True``。
354
+ None。缺少POSIX文件锁的平台沿用同步轮转。
282
355
 
283
356
  Raises:
284
- OSError: 无法检查或打开当前日志文件时抛出。
357
+ OSError: 隔离当前日志失败。
285
358
  """
286
- return int(time.time()) >= self.rolloverAt or RotatingFileHandler.shouldRollover(self, record)
287
-
288
- def rotation_filename(self, default_name):
289
- """生成不覆盖同一时间周期已有归档的文件名。
359
+ if self.compression_opener is None or fcntl is None:
360
+ return super().rotate(source, destination)
361
+ if not os.path.exists(source):
362
+ return
363
+ archive = destination.rsplit('.', 1)[0]
364
+ os.replace(source, archive)
365
+ try:
366
+ if self._compression_pid != os.getpid():
367
+ self._compression_executor = None
368
+ self._compression_pid = os.getpid()
369
+ if self._compression_executor is None:
370
+ # 只回收本日志、已退出进程的压缩候选,完整原始归档仍按既有保留规则管理。
371
+ prefix = f'{Path(self.baseFilename).name}.'
372
+ for entry in os.scandir(Path(self.baseFilename).parent):
373
+ if not entry.is_file(follow_symlinks=False) or not entry.name.startswith(prefix) or '.alaea-compress-' not in entry.name or not entry.name.endswith('.tmp'):
374
+ continue
375
+ archive_name, owner = entry.name.rsplit('.alaea-compress-', 1)
376
+ parts = archive_name[len(prefix):].split('.')
377
+ if not parts or not self.extMatch.fullmatch(parts[0]) or len(parts) > 2 or len(parts) == 2 and not parts[1].isdigit():
378
+ continue
379
+ pid = owner.split('-', 1)[0]
380
+ if not pid.isascii() or not pid.isdigit() or not 0 < int(pid) <= 2 ** 31 - 1:
381
+ continue
382
+ try:
383
+ os.kill(int(pid), 0)
384
+ except ProcessLookupError:
385
+ os.remove(entry.path)
386
+ except PermissionError:
387
+ pass
388
+ self._compression_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='alaea-log-compress')
389
+ self._compression_executor.submit(self._compress_archive, archive, destination)
390
+ except Exception:
391
+ # 任务提交失败也保留完整归档,并让触发轮转的新日志继续写入。
392
+ self.handleError(logging.LogRecord(__name__, logging.ERROR, __file__, 0, '日志后台压缩提交失败,原始归档已保留', (), None))
393
+
394
+ def _compress_archive(self, source, destination):
395
+ """执行后台压缩并将失败交给标准日志错误处理。
290
396
 
291
397
  Args:
292
- default_name: 时间轮转处理器生成的默认归档名。
398
+ source (str): 已隔离的原始归档。
399
+ destination (str): 最终压缩归档。
293
400
 
294
401
  Returns:
295
- 可安全写入的归档文件名;重名时增加数字序号。
402
+ None。失败时保留原始归档及标准错误诊断。
403
+ """
404
+ try:
405
+ _compress_rotated_log(source, destination, self.compression_opener, self)
406
+ except Exception:
407
+ self.handleError(logging.LogRecord(__name__, logging.ERROR, __file__, 0, '日志后台压缩失败,原始归档已保留', (), None))
408
+
409
+ def close(self):
410
+ """排空本进程后台压缩后关闭日志句柄。
411
+
412
+ Returns:
413
+ None。
296
414
 
297
415
  Raises:
298
- OSError: 无法检查归档文件是否存在时抛出。
416
+ BaseException: 等待线程结束被中断,保留线程引用供重试。
299
417
  """
300
- candidate = super().rotation_filename(default_name)
301
- if not os.path.exists(candidate):
302
- return candidate
303
- extension = next((suffix for suffix in ('.zst', '.gz') if candidate.endswith(suffix)), '')
304
- stem = candidate[:-len(extension)] if extension else candidate
305
- sequence = 1
306
- while os.path.exists(f'{stem}.{sequence}{extension}'):
307
- sequence += 1
308
- return f'{stem}.{sequence}{extension}'
418
+ if self._compression_executor is not None and self._compression_pid == os.getpid():
419
+ self._compression_executor.shutdown(wait=True)
420
+ self._compression_executor = None
421
+ super().close()
309
422
 
310
423
  def getFilesToDelete(self):
311
- """查找超过保留数量的最旧组合轮转归档。
424
+ """跨 gzip、zstd 和未压缩格式,查找超过保留数量的最旧时间归档。
312
425
 
313
426
  Returns:
314
- 应在本次轮转后删除的归档路径列表。
427
+ list[str]:按修改时间排序的过量归档;backupCount <= 0 时为空。
315
428
 
316
429
  Raises:
317
430
  OSError: 无法读取日志目录或归档修改时间时抛出。
@@ -319,8 +432,9 @@ class _SizeAndTimeRotatingFileHandler(_ProcessSafeRotatingMixin, TimedRotatingFi
319
432
  directory, basename = os.path.split(self.baseFilename)
320
433
  prefix = f'{basename}.'
321
434
  archives = []
322
- for filename in os.listdir(directory):
323
- if not filename.startswith(prefix) or filename.endswith('.tmp'):
435
+ for entry in os.scandir(directory):
436
+ filename = entry.name
437
+ if not entry.is_file(follow_symlinks=False) or not filename.startswith(prefix) or filename.endswith('.tmp'):
324
438
  continue
325
439
  parts = filename[len(prefix):].split('.')
326
440
  if parts[-1] in {'gz', 'zst'}:
@@ -331,6 +445,47 @@ class _SizeAndTimeRotatingFileHandler(_ProcessSafeRotatingMixin, TimedRotatingFi
331
445
  return archives[:-self.backupCount] if self.backupCount > 0 else []
332
446
 
333
447
 
448
+ class _SizeAndTimeRotatingFileHandler(_ProcessSafeTimedRotatingFileHandler):
449
+ """在时间或文件大小任一条件满足时轮转日志。"""
450
+
451
+ def __init__(self, filename, maxBytes, when, interval, backupCount, encoding='utf-8', delay=True, utc=False):
452
+ """初始化组合轮转处理器。
453
+
454
+ Args:
455
+ filename: 当前日志文件路径。
456
+ maxBytes: 触发轮转的最大字节数;零表示不按大小触发。
457
+ when: 按时间轮转使用的时间单位。
458
+ interval: 时间轮转间隔数量。
459
+ backupCount: 保留的历史文件数量。
460
+ encoding: 日志文件编码。
461
+ delay: 是否延迟到首次写入时打开文件。
462
+ utc: 是否使用 UTC 计算轮转时间。
463
+
464
+ Returns:
465
+ None.
466
+
467
+ Raises:
468
+ ValueError: 时间轮转参数无效时抛出。
469
+ OSError: 无法检查或打开日志文件时抛出。
470
+ """
471
+ super().__init__(filename, when=when, interval=interval, backupCount=backupCount, encoding=encoding,
472
+ delay=delay, utc=utc, atTime=datetime.time(0, 0, 0))
473
+ self.maxBytes = maxBytes
474
+
475
+ def shouldRollover(self, record):
476
+ """判断写入当前记录前是否需要轮转。
477
+
478
+ Args:
479
+ record: 即将写入的日志记录。
480
+
481
+ Returns:
482
+ 时间或大小条件任一满足时返回 ``True``。
483
+
484
+ Raises:
485
+ OSError: 无法检查或打开当前日志文件时抛出。
486
+ """
487
+ return int(time.time()) >= self.rolloverAt or RotatingFileHandler.shouldRollover(self, record)
488
+
334
489
  class Blog:
335
490
  """
336
491
  先创建日志记录器(logging.getLogger),然后再设置日志级别(logger.setLevel),
@@ -687,9 +842,13 @@ class Blog:
687
842
  if compression == 'zstd':
688
843
  handler.namer = self.__zstd_namer
689
844
  handler.rotator = self.__zstd_rotator
845
+ if isinstance(handler, _ProcessSafeTimedRotatingFileHandler):
846
+ handler.compression_opener = zstandard.open
690
847
  elif compression == 'gzip':
691
848
  handler.namer = self.__gzip_namer
692
849
  handler.rotator = self.__gzip_rotator
850
+ if isinstance(handler, _ProcessSafeTimedRotatingFileHandler):
851
+ handler.compression_opener = gzip.open
693
852
  return handler
694
853
 
695
854
  @staticmethod
@@ -711,18 +870,7 @@ class Blog:
711
870
  Raises:
712
871
  OSError: 读取、压缩、替换或删除日志文件失败时抛出。
713
872
  """
714
- temporary_destination = f'{destination}.tmp'
715
- try:
716
- with open(source, 'rb') as source_stream, zstandard.open(temporary_destination, 'wb') as target_stream:
717
- shutil.copyfileobj(source_stream, target_stream)
718
- os.replace(temporary_destination, destination)
719
- os.remove(source)
720
- except BaseException:
721
- try:
722
- os.remove(temporary_destination)
723
- except FileNotFoundError:
724
- pass
725
- raise
873
+ _compress_rotated_log(source, destination, zstandard.open)
726
874
 
727
875
  @staticmethod
728
876
  def __gzip_namer(default_name):
@@ -743,19 +891,8 @@ class Blog:
743
891
  Raises:
744
892
  OSError: 读取、压缩、替换或删除日志文件失败时抛出。
745
893
  """
746
- temporary_destination = f'{destination}.tmp'
747
- try:
748
- with open(source, 'rb') as source_stream, gzip.open(temporary_destination, 'wb') as target_stream:
749
- shutil.copyfileobj(source_stream, target_stream)
750
- os.replace(temporary_destination, destination)
751
- os.remove(source)
752
- except BaseException:
753
- try:
754
- os.remove(temporary_destination)
755
- except FileNotFoundError:
756
- pass
757
- raise
758
-
894
+ _compress_rotated_log(source, destination, gzip.open)
895
+
759
896
  def __set_log_handler(self, logger_handler, level=logging.DEBUG):
760
897
  """
761
898
  设置handler级别并添加到logger收集器
@@ -849,8 +849,9 @@ def calc_dtype(_values) -> type:
849
849
 
850
850
  惰性数组直接沿用其声明 dtype,避免为了编码推断触发整块数据读取;内存数组继续按实际值缩窄。
851
851
 
852
- :param _values: NumPy、Dask 或兼容数组。
853
- :return: NumPy 类型对象,例如 np.float32 或 np.int16。
852
+ :param _values: numpy.ndarray、Dask Array 或兼容数值数组。
853
+ :return: type,NumPy 类型对象;超出 Int64 的有限浮点保留 Float64,超出有符号范围的整数保留 UInt64。
854
+ :raises TypeError: 输入不能表示为受支持的数值数组。
854
855
 
855
856
  返回值为 NumPy 类型对象(如 np.float32 / np.int32),便于直接配合 np.finfo() / np.iinfo() 使用。
856
857
 
@@ -891,6 +892,8 @@ def calc_dtype(_values) -> type:
891
892
  if np.issubdtype(arr.dtype, np.floating):
892
893
  # 没有小数部分 → 按整数处理
893
894
  if np.all(np.equal(arr, np.floor(arr))):
895
+ if np.min(arr) < -(2 ** 63) or np.max(arr) >= 2 ** 63:
896
+ return np.float64
894
897
  arr = arr.astype(np.int64) # 转为整数处理
895
898
  else:
896
899
  # 有小数部分 → 判断 float32 是否够
@@ -905,6 +908,7 @@ def calc_dtype(_values) -> type:
905
908
 
906
909
  # 如果本身是整数 dtype
907
910
  if np.issubdtype(arr.dtype, np.integer):
911
+ valid_min, valid_max = int(valid_min), int(valid_max)
908
912
  if np.iinfo(np.int8).min <= valid_min and valid_max <= np.iinfo(np.int8).max:
909
913
  return np.int8
910
914
  elif np.iinfo(np.int16).min <= valid_min and valid_max <= np.iinfo(np.int16).max:
@@ -914,22 +918,24 @@ def calc_dtype(_values) -> type:
914
918
  elif np.iinfo(np.int64).min <= valid_min and valid_max <= np.iinfo(np.int64).max:
915
919
  return np.int64
916
920
  else:
917
- return np.float64 # 超出整数范围,使用float64存储
921
+ return np.uint64 # 保留超出有符号范围的 UInt64 精度。
918
922
 
919
923
  # 其他情况兜底
920
924
  return np.float32
921
925
 
922
926
 
923
927
  def calc_fillvalue(_dtype):
928
+ """为浮点和有符号整数选择填充值,无符号整数保留完整有效值域。
929
+
930
+ :param _dtype: type | numpy.dtype,输出数据类型。
931
+ :return: 数值填充标记或 None;无符号整数使用 None,避免把合法零值当成缺测并转为浮点。
932
+ :raises TypeError: 无法解析输出数据类型。
924
933
  """
925
- 根据数据类型计算合适的_FillValue
926
- :param _dtype: 数据类型
927
- :return: _FillValue"""
928
934
  dt = np.dtype(_dtype)
929
935
 
930
936
  if np.issubdtype(dt, np.floating):
931
937
  return np.finfo(dt).max
932
- elif np.issubdtype(dt, np.integer):
938
+ elif np.issubdtype(dt, np.signedinteger):
933
939
  return np.iinfo(dt).min
934
940
 
935
941
  return None
@@ -7,6 +7,7 @@ from __future__ import annotations
7
7
  import ctypes
8
8
  import math
9
9
  import os
10
+ import secrets
10
11
  from functools import lru_cache
11
12
  from itertools import product
12
13
  from pathlib import Path
@@ -18,6 +19,8 @@ import xarray as xr
18
19
  from netCDF4 import Dataset
19
20
  from xarray.conventions import encode_cf_variable
20
21
 
22
+ from ..netcdf_input import cleanup_orphaned_input_files
23
+
21
24
  __all__ = ['NetcdfCompressionError', 'write_netcdf']
22
25
 
23
26
  HDF5_ZSTD_FILTER_ID = 32015
@@ -102,9 +105,9 @@ def _copy_values(source: xr.Variable, target: Any, maximum_block_bytes: int = MA
102
105
  while math.prod(block_shape) > maximum_values:
103
106
  index = max(range(source.ndim), key=block_shape.__getitem__)
104
107
  block_shape[index] = max(1, (block_shape[index] + 1) // 2)
105
- starts = [range(0, length, block_length) for length, block_length in zip(source.shape, block_shape, strict=True)]
108
+ starts = [range(0, length, block_length) for length, block_length in zip(source.shape, block_shape)]
106
109
  for offsets in product(*starts):
107
- block_slices = tuple(slice(offset, min(offset + block_length, length)) for offset, block_length, length in zip(offsets, block_shape, source.shape, strict=True))
110
+ block_slices = tuple(slice(offset, min(offset + block_length, length)) for offset, block_length, length in zip(offsets, block_shape, source.shape))
108
111
  target[block_slices] = np.asarray(source.data[block_slices])
109
112
 
110
113
 
@@ -129,7 +132,7 @@ def _write_zstd(_ds: xr.Dataset, path: Path, complevel: int, shuffle: bool) -> N
129
132
  char_dimension = encoding.get('char_dim_name')
130
133
  if char_dimension:
131
134
  strings = np.asarray(source.values).astype(str)
132
- width = max(1, max(len(value.encode('utf-8')) for value in strings.reshape(-1)))
135
+ width = max(1, max((len(value.encode('utf-8')) for value in strings.reshape(-1)), default=1))
133
136
  if char_dimension not in output.dimensions:
134
137
  output.createDimension(char_dimension, width)
135
138
  target = output.createVariable(name, 'S1', source.dims + (char_dimension,))
@@ -191,7 +194,8 @@ def _validate_compression(path: Path, compression: str, complevel: int, shuffle:
191
194
  expected_compressed = complevel > 0
192
195
  if bool(filters.get(compression)) != expected_compressed or bool(filters.get('zstd' if compression == 'zlib' else 'zlib')) or bool(filters.get('shuffle')) != bool(shuffle and expected_compressed) or expected_compressed and filters.get('complevel') != complevel:
193
196
  raise NetcdfCompressionError(f'NetCDF 变量 {variable.name} 的实际压缩管线不符合写入参数')
194
- variable[tuple(0 for _ in variable.dimensions)]
197
+ if all(variable.shape):
198
+ variable[tuple(0 for _ in variable.dimensions)]
195
199
  except NetcdfCompressionError:
196
200
  raise
197
201
  except Exception as error:
@@ -199,20 +203,21 @@ def _validate_compression(path: Path, compression: str, complevel: int, shuffle:
199
203
 
200
204
 
201
205
  def write_netcdf(_ds: xr.Dataset, _path: Union[str, os.PathLike], compression: str = 'zlib', complevel: int = 4, shuffle: bool = True, engine: str = 'h5netcdf') -> Path:
202
- """将 Dataset 写为 zlib 或标准 HDF5 Zstd filter 32015 NetCDF4 文件。
206
+ """校验完整候选后原子发布 zlib 或标准 HDF5 Zstd filter 32015 NetCDF4 文件。
203
207
 
204
208
  默认 zlib 继续调用 xarray 原生写入;选择 zstd 时显式创建 ``shuffle(2) -> 32015`` 管线,
205
209
  缺少插件会失败而不会静默降级。
206
210
 
207
- :param _ds: 待写出的 xarray.Dataset。
208
- :param _path: 输出文件路径。
209
- :param compression: ``zlib``(默认)或 ``zstd``。
210
- :param complevel: zlib 支持 0-9,Zstd 支持 0-22;0 表示不压缩。
211
- :param shuffle: 是否在压缩前执行 HDF5 byte shuffle。
212
- :param engine: zlib 分支使用的 xarray 后端,默认 h5netcdf;Zstd 分支固定使用 netCDF4。
213
- :return: 完整输出 Path。
211
+ :param _ds: xarray.Dataset,待写出的数据。
212
+ :param _path: str | os.PathLike,输出文件路径。
213
+ :param compression: str,``zlib``(默认)或 ``zstd``。
214
+ :param complevel: int,zlib 支持 0-9,Zstd 支持 0-22;0 表示不压缩。
215
+ :param shuffle: bool,是否在压缩前执行 HDF5 byte shuffle。
216
+ :param engine: str,zlib 分支使用的 xarray 后端,默认 h5netcdf;Zstd 固定使用 netCDF4。
217
+ :return: Path,完整输出路径;失败或取消时保留已有输出。POSIX 下次写入同目录时回收本库已退出进程的候选。
214
218
  :raises ValueError: 压缩格式、级别或输入类型非法。
215
219
  :raises NetcdfCompressionError: Zstd 插件或实际写入失败。
220
+ :raises OSError: 候选创建、写入、校验或发布失败。
216
221
  """
217
222
  if not isinstance(_ds, xr.Dataset):
218
223
  raise ValueError('_ds 必须是 xarray.Dataset')
@@ -224,9 +229,17 @@ def write_netcdf(_ds: xr.Dataset, _path: Union[str, os.PathLike], compression: s
224
229
  raise ValueError(f'{compression} complevel 必须位于 0-{maximum_level}')
225
230
  path = Path(_path)
226
231
  path.parent.mkdir(parents=True, exist_ok=True)
232
+ prefix = '.alaea-netcdf-write-'
233
+ cleanup_orphaned_input_files(path.parent, prefixes=(prefix,))
234
+ temporary = path.with_name(f'{prefix}{os.getpid()}-{secrets.token_hex(8)}.nc')
235
+ # 独占创建遵循当前 umask,覆盖时沿用已有输出的访问权限。
236
+ with temporary.open('xb'):
237
+ pass
227
238
  try:
239
+ if path.exists():
240
+ temporary.chmod(path.stat().st_mode & 0o777)
228
241
  if compression == 'zstd':
229
- _write_zstd(_ds, path, complevel, bool(shuffle))
242
+ _write_zstd(_ds, temporary, complevel, bool(shuffle))
230
243
  else:
231
244
  dataset = _ds.copy(deep=False)
232
245
  dataset.attrs = dict(_ds.attrs) | {'alaea_compression_codec': 'zlib', 'alaea_compression_level': complevel, 'alaea_shuffle_mode': 'byte' if shuffle and complevel > 0 else 'none'}
@@ -234,9 +247,9 @@ def write_netcdf(_ds: xr.Dataset, _path: Union[str, os.PathLike], compression: s
234
247
  dataset[name].encoding = dict(_ds[name].encoding)
235
248
  if dataset[name].dims and (np.issubdtype(dataset[name].dtype, np.number) or dataset[name].dtype.kind in {'M', 'm'}):
236
249
  dataset[name].encoding.update({'zlib': complevel > 0, 'complevel': complevel, 'shuffle': bool(shuffle and complevel > 0)})
237
- dataset.to_netcdf(path, engine=engine)
238
- _validate_compression(path, compression, complevel, bool(shuffle))
239
- except Exception:
240
- path.unlink(missing_ok=True)
241
- raise
250
+ dataset.to_netcdf(temporary, engine=engine)
251
+ _validate_compression(temporary, compression, complevel, bool(shuffle))
252
+ os.replace(temporary, path)
253
+ finally:
254
+ temporary.unlink(missing_ok=True)
242
255
  return path