das-cli 1.7.8__tar.gz → 1.9.0__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.
- {das_cli-1.7.8/das_cli.egg-info → das_cli-1.9.0}/PKG-INFO +62 -1
- {das_cli-1.7.8 → das_cli-1.9.0}/README.md +61 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/cli.py +69 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/managers/entries_manager.py +152 -41
- das_cli-1.9.0/das/services/hangfire.py +101 -0
- {das_cli-1.7.8 → das_cli-1.9.0/das_cli.egg-info}/PKG-INFO +62 -1
- {das_cli-1.7.8 → das_cli-1.9.0}/pyproject.toml +1 -1
- das_cli-1.7.8/das/services/hangfire.py +0 -19
- {das_cli-1.7.8 → das_cli-1.9.0}/LICENSE +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/MANIFEST.in +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/__init__.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/ai/plugins/dasai.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/ai/plugins/entries/entries_plugin.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/app.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/authentication/auth.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/authentication/oauth.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/authentication/secure_input.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/common/api.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/common/config.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/common/entry_fields_constants.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/common/enums.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/common/errors.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/common/exceptions.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/common/file_utils.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/managers/__init__.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/managers/digital_objects_manager.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/managers/download_manager.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/managers/search_manager.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/services/attributes.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/services/cache.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/services/das_elastic_search.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/services/digital_objects.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/services/downloads.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/services/entries.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/services/entry_fields.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/services/search.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/services/service_base.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/services/session.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das/services/users.py +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das_cli.egg-info/SOURCES.txt +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das_cli.egg-info/dependency_links.txt +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das_cli.egg-info/entry_points.txt +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das_cli.egg-info/requires.txt +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/das_cli.egg-info/top_level.txt +0 -0
- {das_cli-1.7.8 → das_cli-1.9.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: das-cli
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.9.0
|
|
4
4
|
Summary: DAS api client.
|
|
5
5
|
Author: Royal Netherlands Institute for Sea Research
|
|
6
6
|
License-Expression: MIT
|
|
@@ -301,6 +301,12 @@ das cache list
|
|
|
301
301
|
das cache clear "attributes"
|
|
302
302
|
das cache clear-all
|
|
303
303
|
|
|
304
|
+
# Hangfire (background jobs) — needs the Hangfire dashboard permission
|
|
305
|
+
das hangfire list # recurring jobs: ID, cron, queue, last/next run
|
|
306
|
+
das hangfire list --format json
|
|
307
|
+
das hangfire trigger "5. harvest-archive" # run a recurring job now (quote IDs with spaces)
|
|
308
|
+
das hangfire sync-doi <entry-id>
|
|
309
|
+
|
|
304
310
|
# Config
|
|
305
311
|
das config ssl-verify true
|
|
306
312
|
das config ssl-status
|
|
@@ -407,6 +413,34 @@ if info["status"] == "valid":
|
|
|
407
413
|
`get_current_user()` and `validate_api_key(key)` — the last one checks a key
|
|
408
414
|
without storing it.
|
|
409
415
|
|
|
416
|
+
### Recurring Hangfire jobs
|
|
417
|
+
|
|
418
|
+
Every recurring job the DAS worker registers can be listed and run on demand —
|
|
419
|
+
the equivalent of *Trigger now* in the `/hangfire` dashboard. Triggering
|
|
420
|
+
enqueues one extra run; the job's schedule is not changed. Your account needs
|
|
421
|
+
the **Hangfire dashboard** permission (`Pages.Administration.HangfireDashboard`).
|
|
422
|
+
|
|
423
|
+
```python
|
|
424
|
+
from das.app import Das
|
|
425
|
+
|
|
426
|
+
das = Das() # uses the URL + credential saved by `das login`
|
|
427
|
+
|
|
428
|
+
for job in das.hangfire.get_recurring_jobs():
|
|
429
|
+
print(job["id"], job["cron"], job["queue"], job["nextExecution"], job["lastJobState"])
|
|
430
|
+
|
|
431
|
+
result = das.hangfire.trigger_recurring_job("5. harvest-archive")
|
|
432
|
+
print(result["jobId"]) # id of the background job that was enqueued
|
|
433
|
+
|
|
434
|
+
# Case-insensitive lookup; raises ValueError listing the valid ids when unknown
|
|
435
|
+
job = das.hangfire.find_recurring_job("system health check")
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
Each job is a dict with `id`, `cron`, `queue`, `timeZoneId`, `job`
|
|
439
|
+
(`Type.Method`), `nextExecution`, `lastExecution`, `lastJobId`, `lastJobState`,
|
|
440
|
+
`createdAt` and `error`; timestamps are UTC. Failures raise a `DasApiError`
|
|
441
|
+
subclass (e.g. `DasPermissionError` without the permission, `DasNotFoundError`
|
|
442
|
+
when the server is too old to have these endpoints).
|
|
443
|
+
|
|
410
444
|
## Manager Layer API Reference (Domain Layer)
|
|
411
445
|
|
|
412
446
|
Managers are the recommended Python API. They translate user-friendly field names, codes, and query syntax into the lower-level DAS API calls.
|
|
@@ -511,6 +545,11 @@ result = entries.create(attribute="Cores", entry={
|
|
|
511
545
|
# result -> [{"id": "<guid>", "code": "zb.b.xxx", "status": "success"}]
|
|
512
546
|
new_id = result[0]["id"]
|
|
513
547
|
|
|
548
|
+
# The code is generated by the server and read back with a second request.
|
|
549
|
+
# Skip that request when only the id is needed (imports, benchmarks):
|
|
550
|
+
result = entries.create(attribute="Cores", entry={...}, fetch_code=False)
|
|
551
|
+
# result -> [{"id": "<guid>", "status": "success"}]
|
|
552
|
+
|
|
514
553
|
# Bulk create
|
|
515
554
|
results = entries.create(attribute="Cores", entries=[
|
|
516
555
|
{"Alias": "bulk.001", "Event": "64PE428-02PC", "Number": 1},
|
|
@@ -529,6 +568,28 @@ entries.create(attribute="Cruise", entry={
|
|
|
529
568
|
})
|
|
530
569
|
```
|
|
531
570
|
|
|
571
|
+
#### `warm_select_cache` — pre-resolve select values before an import
|
|
572
|
+
|
|
573
|
+
Every select field value (`"Event": "64PE428-02PC"`, `"Device": "CTD"`) is
|
|
574
|
+
resolved with one search request the first time the manager sees it. An
|
|
575
|
+
import that references many different stations, devices or cruises pays one
|
|
576
|
+
request per distinct value. `warm_select_cache` loads the options of every
|
|
577
|
+
select field of an attribute up front and caches them by code, display name
|
|
578
|
+
and id, so the rows that follow resolve without a request:
|
|
579
|
+
|
|
580
|
+
```python
|
|
581
|
+
entries = EntryManager()
|
|
582
|
+
cached = entries.warm_select_cache("Event") # one request per select field (per 1000 options)
|
|
583
|
+
print(f"{cached} select options cached")
|
|
584
|
+
|
|
585
|
+
for row in rows:
|
|
586
|
+
entries.create(attribute="Event", entry=row, fetch_code=False) # one request per row
|
|
587
|
+
```
|
|
588
|
+
|
|
589
|
+
Values must match the server's spelling and case; anything else still falls
|
|
590
|
+
back to a search. Fields with more than `max_results` options (default 1000)
|
|
591
|
+
are warmed partially. The cache lives as long as the manager instance.
|
|
592
|
+
|
|
532
593
|
#### `update` — update one or many entries
|
|
533
594
|
|
|
534
595
|
```python
|
|
@@ -278,6 +278,12 @@ das cache list
|
|
|
278
278
|
das cache clear "attributes"
|
|
279
279
|
das cache clear-all
|
|
280
280
|
|
|
281
|
+
# Hangfire (background jobs) — needs the Hangfire dashboard permission
|
|
282
|
+
das hangfire list # recurring jobs: ID, cron, queue, last/next run
|
|
283
|
+
das hangfire list --format json
|
|
284
|
+
das hangfire trigger "5. harvest-archive" # run a recurring job now (quote IDs with spaces)
|
|
285
|
+
das hangfire sync-doi <entry-id>
|
|
286
|
+
|
|
281
287
|
# Config
|
|
282
288
|
das config ssl-verify true
|
|
283
289
|
das config ssl-status
|
|
@@ -384,6 +390,34 @@ if info["status"] == "valid":
|
|
|
384
390
|
`get_current_user()` and `validate_api_key(key)` — the last one checks a key
|
|
385
391
|
without storing it.
|
|
386
392
|
|
|
393
|
+
### Recurring Hangfire jobs
|
|
394
|
+
|
|
395
|
+
Every recurring job the DAS worker registers can be listed and run on demand —
|
|
396
|
+
the equivalent of *Trigger now* in the `/hangfire` dashboard. Triggering
|
|
397
|
+
enqueues one extra run; the job's schedule is not changed. Your account needs
|
|
398
|
+
the **Hangfire dashboard** permission (`Pages.Administration.HangfireDashboard`).
|
|
399
|
+
|
|
400
|
+
```python
|
|
401
|
+
from das.app import Das
|
|
402
|
+
|
|
403
|
+
das = Das() # uses the URL + credential saved by `das login`
|
|
404
|
+
|
|
405
|
+
for job in das.hangfire.get_recurring_jobs():
|
|
406
|
+
print(job["id"], job["cron"], job["queue"], job["nextExecution"], job["lastJobState"])
|
|
407
|
+
|
|
408
|
+
result = das.hangfire.trigger_recurring_job("5. harvest-archive")
|
|
409
|
+
print(result["jobId"]) # id of the background job that was enqueued
|
|
410
|
+
|
|
411
|
+
# Case-insensitive lookup; raises ValueError listing the valid ids when unknown
|
|
412
|
+
job = das.hangfire.find_recurring_job("system health check")
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
Each job is a dict with `id`, `cron`, `queue`, `timeZoneId`, `job`
|
|
416
|
+
(`Type.Method`), `nextExecution`, `lastExecution`, `lastJobId`, `lastJobState`,
|
|
417
|
+
`createdAt` and `error`; timestamps are UTC. Failures raise a `DasApiError`
|
|
418
|
+
subclass (e.g. `DasPermissionError` without the permission, `DasNotFoundError`
|
|
419
|
+
when the server is too old to have these endpoints).
|
|
420
|
+
|
|
387
421
|
## Manager Layer API Reference (Domain Layer)
|
|
388
422
|
|
|
389
423
|
Managers are the recommended Python API. They translate user-friendly field names, codes, and query syntax into the lower-level DAS API calls.
|
|
@@ -488,6 +522,11 @@ result = entries.create(attribute="Cores", entry={
|
|
|
488
522
|
# result -> [{"id": "<guid>", "code": "zb.b.xxx", "status": "success"}]
|
|
489
523
|
new_id = result[0]["id"]
|
|
490
524
|
|
|
525
|
+
# The code is generated by the server and read back with a second request.
|
|
526
|
+
# Skip that request when only the id is needed (imports, benchmarks):
|
|
527
|
+
result = entries.create(attribute="Cores", entry={...}, fetch_code=False)
|
|
528
|
+
# result -> [{"id": "<guid>", "status": "success"}]
|
|
529
|
+
|
|
491
530
|
# Bulk create
|
|
492
531
|
results = entries.create(attribute="Cores", entries=[
|
|
493
532
|
{"Alias": "bulk.001", "Event": "64PE428-02PC", "Number": 1},
|
|
@@ -506,6 +545,28 @@ entries.create(attribute="Cruise", entry={
|
|
|
506
545
|
})
|
|
507
546
|
```
|
|
508
547
|
|
|
548
|
+
#### `warm_select_cache` — pre-resolve select values before an import
|
|
549
|
+
|
|
550
|
+
Every select field value (`"Event": "64PE428-02PC"`, `"Device": "CTD"`) is
|
|
551
|
+
resolved with one search request the first time the manager sees it. An
|
|
552
|
+
import that references many different stations, devices or cruises pays one
|
|
553
|
+
request per distinct value. `warm_select_cache` loads the options of every
|
|
554
|
+
select field of an attribute up front and caches them by code, display name
|
|
555
|
+
and id, so the rows that follow resolve without a request:
|
|
556
|
+
|
|
557
|
+
```python
|
|
558
|
+
entries = EntryManager()
|
|
559
|
+
cached = entries.warm_select_cache("Event") # one request per select field (per 1000 options)
|
|
560
|
+
print(f"{cached} select options cached")
|
|
561
|
+
|
|
562
|
+
for row in rows:
|
|
563
|
+
entries.create(attribute="Event", entry=row, fetch_code=False) # one request per row
|
|
564
|
+
```
|
|
565
|
+
|
|
566
|
+
Values must match the server's spelling and case; anything else still falls
|
|
567
|
+
back to a search. Fields with more than `max_results` options (default 1000)
|
|
568
|
+
are warmed partially. The cache lives as long as the manager instance.
|
|
569
|
+
|
|
509
570
|
#### `update` — update one or many entries
|
|
510
571
|
|
|
511
572
|
```python
|
|
@@ -613,6 +613,75 @@ def sync_doi(das_ctx, id):
|
|
|
613
613
|
except Exception as e:
|
|
614
614
|
click.secho(f"Error: {e}", fg="red")
|
|
615
615
|
|
|
616
|
+
def _format_job_time(value):
|
|
617
|
+
"""Render a Hangfire UTC timestamp as 'YYYY-MM-DD HH:MM:SS' ('-' when empty)."""
|
|
618
|
+
if not value:
|
|
619
|
+
return "-"
|
|
620
|
+
text = str(value)
|
|
621
|
+
if "T" not in text:
|
|
622
|
+
return text
|
|
623
|
+
date_part, time_part = text.split("T", 1)
|
|
624
|
+
return f"{date_part} {time_part.split('.')[0].rstrip('Z')[:8]}"
|
|
625
|
+
|
|
626
|
+
@hangfire.command("list")
|
|
627
|
+
@click.option('--format', 'output_format', default='table', type=click.Choice(['table', 'json']), help='Output format (table or json)')
|
|
628
|
+
@pass_das_context
|
|
629
|
+
def list_recurring_jobs(das_ctx, output_format):
|
|
630
|
+
"""List the recurring jobs (ID, schedule, queue, last/next run)"""
|
|
631
|
+
try:
|
|
632
|
+
client = das_ctx.get_client()
|
|
633
|
+
jobs = client.hangfire.get_recurring_jobs()
|
|
634
|
+
|
|
635
|
+
if output_format == 'json':
|
|
636
|
+
click.echo(json.dumps(jobs, indent=2))
|
|
637
|
+
return
|
|
638
|
+
|
|
639
|
+
if not jobs:
|
|
640
|
+
click.secho("No recurring jobs found.", fg="yellow")
|
|
641
|
+
return
|
|
642
|
+
|
|
643
|
+
headers = ["ID", "Cron", "Queue", "Next run (UTC)", "Last run (UTC)", "Last state"]
|
|
644
|
+
table_data = [
|
|
645
|
+
[
|
|
646
|
+
job.get('id') or "",
|
|
647
|
+
job.get('cron') or "",
|
|
648
|
+
job.get('queue') or "",
|
|
649
|
+
_format_job_time(job.get('nextExecution')),
|
|
650
|
+
_format_job_time(job.get('lastExecution')),
|
|
651
|
+
job.get('lastJobState') or "-",
|
|
652
|
+
]
|
|
653
|
+
for job in jobs
|
|
654
|
+
]
|
|
655
|
+
click.echo(format_table(table_data, headers))
|
|
656
|
+
|
|
657
|
+
for job in jobs:
|
|
658
|
+
if job.get('error'):
|
|
659
|
+
click.secho(f"! {job.get('id')}: {job.get('error')}", fg="yellow")
|
|
660
|
+
|
|
661
|
+
click.echo("\nTrigger one with: das hangfire trigger \"<ID>\"")
|
|
662
|
+
except Exception as e:
|
|
663
|
+
click.secho(f"Error: {e}", fg="red")
|
|
664
|
+
|
|
665
|
+
@hangfire.command("trigger")
|
|
666
|
+
@click.argument('id', required=True)
|
|
667
|
+
@pass_das_context
|
|
668
|
+
def trigger_recurring_job(das_ctx, id):
|
|
669
|
+
"""Run a recurring job now, by its ID (see 'das hangfire list')
|
|
670
|
+
|
|
671
|
+
Quote IDs that contain spaces, e.g. das hangfire trigger "5. harvest-archive"
|
|
672
|
+
"""
|
|
673
|
+
try:
|
|
674
|
+
client = das_ctx.get_client()
|
|
675
|
+
job = client.hangfire.find_recurring_job(id)
|
|
676
|
+
result = client.hangfire.trigger_recurring_job(job.get('id'))
|
|
677
|
+
click.secho(f"✓ Recurring job '{result.get('id') or job.get('id')}' triggered!", fg="green")
|
|
678
|
+
if result.get('jobId'):
|
|
679
|
+
click.echo(f"Background job id: {result.get('jobId')}")
|
|
680
|
+
if job.get('queue'):
|
|
681
|
+
click.echo(f"Queue: {job.get('queue')}")
|
|
682
|
+
except Exception as e:
|
|
683
|
+
click.secho(f"Error: {e}", fg="red")
|
|
684
|
+
|
|
616
685
|
# Elastic Search commands group
|
|
617
686
|
@cli.group()
|
|
618
687
|
def elastic():
|
|
@@ -248,7 +248,7 @@ class EntryManager:
|
|
|
248
248
|
except Exception as e:
|
|
249
249
|
raise ValueError(f"Error processing entry data: {e}")
|
|
250
250
|
|
|
251
|
-
def create(self, attribute: str, entry: dict = None, entries: list = None) -> list:
|
|
251
|
+
def create(self, attribute: str, entry: dict = None, entries: list = None, fetch_code: bool = True) -> list:
|
|
252
252
|
"""
|
|
253
253
|
Create one or more new entries.
|
|
254
254
|
|
|
@@ -256,6 +256,11 @@ class EntryManager:
|
|
|
256
256
|
attribute (str): The attribute name
|
|
257
257
|
entry (dict, optional): Single entry data
|
|
258
258
|
entries (list, optional): List of entry data for creating multiple entries
|
|
259
|
+
fetch_code (bool, optional): For a single ``entry``, also read the
|
|
260
|
+
new entry back to report its server-generated ``code``. That is
|
|
261
|
+
a second request per entry; pass ``False`` when only the id is
|
|
262
|
+
needed (e.g. imports). Ignored for ``entries``, which never
|
|
263
|
+
reports codes.
|
|
259
264
|
|
|
260
265
|
Returns:
|
|
261
266
|
list: List of created entry IDs with status information
|
|
@@ -290,7 +295,9 @@ class EntryManager:
|
|
|
290
295
|
elif entry is not None:
|
|
291
296
|
# Single entry creation
|
|
292
297
|
result = self._create_single_entry(attribute, entry)
|
|
293
|
-
|
|
298
|
+
if not fetch_code:
|
|
299
|
+
return [{"id": result, "status": "success"}]
|
|
300
|
+
# The server generates the code; Create only returns the id.
|
|
294
301
|
new_entry_code = self.entry_service.get(id=result).get('entry').get('code')
|
|
295
302
|
return [{"id": result, "code": new_entry_code, "status": "success"}]
|
|
296
303
|
|
|
@@ -613,7 +620,44 @@ class EntryManager:
|
|
|
613
620
|
# Scalars (ints/floats/bools from files) need to be strings to query.
|
|
614
621
|
source = _coerce_to_str(source)
|
|
615
622
|
|
|
623
|
+
attribute_id, is_multiselect = self.__parse_select_field(field)
|
|
624
|
+
|
|
625
|
+
expected_max_result_count = 1
|
|
626
|
+
if is_multiselect:
|
|
627
|
+
expected_max_result_count = len(source.split(','))
|
|
628
|
+
|
|
629
|
+
search_params = {
|
|
630
|
+
"attributeId": attribute_id,
|
|
631
|
+
"queryString": self.__get_query_string(source, is_multiselect),
|
|
632
|
+
"maxResultCount": expected_max_result_count,
|
|
633
|
+
"skipCount": 0
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
cache_key = (attribute_id, search_params["queryString"], expected_max_result_count)
|
|
637
|
+
if cache_key in self._select_value_cache:
|
|
638
|
+
return self._select_value_cache[cache_key]
|
|
639
|
+
|
|
640
|
+
search_response = self.search_service.search_entries(**search_params)
|
|
641
|
+
|
|
642
|
+
if search_response.get('totalCount', 0) == 0:
|
|
643
|
+
raise ValueError(f"No results found for {field.get('displayName')}: {source}. Attribute ID: {attribute_id}")
|
|
644
|
+
if search_response and 'items' in search_response and len(search_response['items']) > 0:
|
|
645
|
+
result_list = [self.__select_item_to_result(item, attribute_id) for item in search_response['items']]
|
|
646
|
+
value = json.dumps(result_list)
|
|
647
|
+
self._select_value_cache[cache_key] = value
|
|
648
|
+
return value
|
|
649
|
+
else:
|
|
650
|
+
return source
|
|
651
|
+
|
|
652
|
+
def __parse_select_field(self, field) -> tuple:
|
|
653
|
+
"""Return ``(datasource attribute id, is_multiselect)`` of a select field.
|
|
654
|
+
|
|
655
|
+
The attribute the options come from is declared in the field's custom
|
|
656
|
+
data (``datasource.attributeId``); older fields encode it in the column
|
|
657
|
+
name (``x27`` / ``27``). ``-1`` when neither is present.
|
|
658
|
+
"""
|
|
616
659
|
attribute_id = -1
|
|
660
|
+
is_multiselect = False
|
|
617
661
|
|
|
618
662
|
# convert all keys to lowercase
|
|
619
663
|
field = {str(k).lower(): v for k, v in field.items()}
|
|
@@ -625,9 +669,6 @@ class EntryManager:
|
|
|
625
669
|
elif len(column) >= 2 and column[0].isalpha() and column[1:].isdigit():
|
|
626
670
|
attribute_id = int(column[1:])
|
|
627
671
|
|
|
628
|
-
customdata = None
|
|
629
|
-
is_multiselect = False
|
|
630
|
-
|
|
631
672
|
if not field.get('customdata', None) is None and field.get('customdata') != "":
|
|
632
673
|
try:
|
|
633
674
|
customdata_string = field.get('customdata').lower()
|
|
@@ -642,42 +683,112 @@ class EntryManager:
|
|
|
642
683
|
except json.JSONDecodeError:
|
|
643
684
|
raise ValueError(f"Invalid customdata JSON: {field.get('customdata')}")
|
|
644
685
|
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
686
|
+
return attribute_id, bool(is_multiselect)
|
|
687
|
+
|
|
688
|
+
@staticmethod
|
|
689
|
+
def __select_item_to_result(item: dict, attribute_id) -> dict:
|
|
690
|
+
"""Shape one search hit the way the server expects a select value."""
|
|
691
|
+
entry = item.get('entry', {}) or {}
|
|
692
|
+
result = {
|
|
693
|
+
'id': entry.get('id'),
|
|
694
|
+
'name': entry.get('displayname'),
|
|
695
|
+
'code': entry.get('code'),
|
|
696
|
+
'alias': entry.get('alias', None),
|
|
697
|
+
'acronym': entry.get('acronym', None),
|
|
698
|
+
'attributeid': attribute_id,
|
|
654
699
|
}
|
|
655
|
-
|
|
656
|
-
cache_key = (attribute_id, search_params["queryString"], expected_max_result_count)
|
|
657
|
-
if cache_key in self._select_value_cache:
|
|
658
|
-
return self._select_value_cache[cache_key]
|
|
700
|
+
return {k: v for k, v in result.items() if v is not None}
|
|
659
701
|
|
|
660
|
-
|
|
702
|
+
def __iter_select_fields(self, fields: list):
|
|
703
|
+
"""Yield every select field of an attribute, including those nested in a group box."""
|
|
704
|
+
for field in fields:
|
|
705
|
+
if field.get('inputType') == GROUP_BOX_INPUT:
|
|
706
|
+
custom_data = field.get('customData', None)
|
|
707
|
+
if custom_data is None:
|
|
708
|
+
continue
|
|
709
|
+
try:
|
|
710
|
+
nested = json.loads(custom_data).get('fields') or []
|
|
711
|
+
except (json.JSONDecodeError, AttributeError):
|
|
712
|
+
continue
|
|
713
|
+
for nested_field in nested:
|
|
714
|
+
if isinstance(nested_field, dict) and nested_field.get('inputType') == SELECT_COMBO_INPUT:
|
|
715
|
+
yield nested_field
|
|
716
|
+
elif field.get('inputType') == SELECT_COMBO_INPUT:
|
|
717
|
+
yield field
|
|
718
|
+
|
|
719
|
+
def warm_select_cache(self, attribute: str, max_results: int = 1000, page_size: int = 1000) -> int:
|
|
720
|
+
"""Pre-resolve the options of every select field of an attribute.
|
|
721
|
+
|
|
722
|
+
Resolving a select value (``"Device": "CTD"``) normally costs one
|
|
723
|
+
search request the first time each value is seen. For an import that
|
|
724
|
+
references many different stations, devices, cruises, etc. that is one
|
|
725
|
+
request per distinct value. This loads the options of each select
|
|
726
|
+
field up front (one request per page of ``page_size`` options) and
|
|
727
|
+
caches them under their code, display name and id, so later
|
|
728
|
+
``create``/``update`` calls resolve those values without a request.
|
|
729
|
+
|
|
730
|
+
Values must be given exactly as the server returns them (same case);
|
|
731
|
+
anything else still falls back to a search, as before. The cache
|
|
732
|
+
lives as long as this manager.
|
|
661
733
|
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
734
|
+
Args:
|
|
735
|
+
attribute (str): The attribute whose select fields to warm.
|
|
736
|
+
max_results (int, optional): Options to load per select field.
|
|
737
|
+
Fields with more options than this are warmed partially.
|
|
738
|
+
page_size (int, optional): Options per search request.
|
|
739
|
+
|
|
740
|
+
Returns:
|
|
741
|
+
int: Number of options cached.
|
|
742
|
+
"""
|
|
743
|
+
if not attribute:
|
|
744
|
+
raise ValueError("Attribute name is required")
|
|
745
|
+
if max_results <= 0 or page_size <= 0:
|
|
746
|
+
raise ValueError("max_results and page_size must be positive")
|
|
747
|
+
|
|
748
|
+
attribute_id = self.attribute_service.get_id(name=attribute)
|
|
749
|
+
entry_fields_response = self.entry_fields_service.get_entry_fields(attribute_id=attribute_id)
|
|
750
|
+
fields = entry_fields_response.get("result", {}).get("items", [])
|
|
751
|
+
|
|
752
|
+
warmed = 0
|
|
753
|
+
seen_sources = set()
|
|
754
|
+
|
|
755
|
+
for field in self.__iter_select_fields(fields):
|
|
756
|
+
source_attribute_id, is_multiselect = self.__parse_select_field(field)
|
|
757
|
+
if source_attribute_id is None or int(source_attribute_id) < 0 or source_attribute_id in seen_sources:
|
|
758
|
+
continue
|
|
759
|
+
seen_sources.add(source_attribute_id)
|
|
760
|
+
|
|
761
|
+
skip = 0
|
|
762
|
+
while skip < max_results:
|
|
763
|
+
response = self.search_service.search_entries(
|
|
764
|
+
attributeId=source_attribute_id,
|
|
765
|
+
queryString="",
|
|
766
|
+
maxResultCount=min(page_size, max_results - skip),
|
|
767
|
+
skipCount=skip,
|
|
768
|
+
)
|
|
769
|
+
items = (response or {}).get('items') or []
|
|
770
|
+
if not items:
|
|
771
|
+
break
|
|
772
|
+
|
|
773
|
+
for item in items:
|
|
774
|
+
result = self.__select_item_to_result(item, source_attribute_id)
|
|
775
|
+
value = json.dumps([result])
|
|
776
|
+
for key in (result.get('code'), result.get('name'), result.get('id')):
|
|
777
|
+
if _is_empty(key):
|
|
778
|
+
continue
|
|
779
|
+
key = _coerce_to_str(key)
|
|
780
|
+
# A field is either single- or multi-select; a one-value
|
|
781
|
+
# multiselect uses a different query string, so cache
|
|
782
|
+
# the one this field will actually ask for.
|
|
783
|
+
query = self.__get_query_string(key, is_multiselect)
|
|
784
|
+
self._select_value_cache[(source_attribute_id, query, 1)] = value
|
|
785
|
+
warmed += 1
|
|
786
|
+
|
|
787
|
+
skip += len(items)
|
|
788
|
+
if skip >= (response.get('totalCount') or 0):
|
|
789
|
+
break
|
|
790
|
+
|
|
791
|
+
return warmed
|
|
681
792
|
|
|
682
793
|
def __get_query_string(self, source: str, is_multiselect: bool) -> str:
|
|
683
794
|
|
|
@@ -839,7 +950,7 @@ class EntryManager:
|
|
|
839
950
|
for entry in entries:
|
|
840
951
|
if not isinstance(entry, dict):
|
|
841
952
|
raise ValueError("Each entry must be a dictionary")
|
|
842
|
-
self.create(attribute=attribute, entry=entry)
|
|
953
|
+
self.create(attribute=attribute, entry=entry, fetch_code=False)
|
|
843
954
|
|
|
844
955
|
def __create_from_csv_file(self, attribute: str, file_path: str):
|
|
845
956
|
"""Create a set of new entries from a file."""
|
|
@@ -851,7 +962,7 @@ class EntryManager:
|
|
|
851
962
|
entries = [row for row in reader]
|
|
852
963
|
|
|
853
964
|
for entry in entries:
|
|
854
|
-
self.create(attribute=attribute, entry=entry)
|
|
965
|
+
self.create(attribute=attribute, entry=entry, fetch_code=False)
|
|
855
966
|
|
|
856
967
|
|
|
857
968
|
def __create_from_excel_file(self, attribute: str, file_path: str):
|
|
@@ -866,7 +977,7 @@ class EntryManager:
|
|
|
866
977
|
entries = df.to_dict(orient='records')
|
|
867
978
|
|
|
868
979
|
for entry in entries:
|
|
869
|
-
self.create(attribute=attribute, entry=entry)
|
|
980
|
+
self.create(attribute=attribute, entry=entry, fetch_code=False)
|
|
870
981
|
|
|
871
982
|
|
|
872
983
|
def create_from_file(self, attribute: str, file_path: str):
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from das.common.api import get_data, post_data
|
|
2
|
+
from das.common.errors import build_api_error, extract_api_error
|
|
3
|
+
from das.common.exceptions import DasNotFoundError
|
|
4
|
+
from das.services.service_base import ServiceBase
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class HangfireService(ServiceBase):
|
|
8
|
+
def __init__(self, base_url):
|
|
9
|
+
self.base_url = f"{base_url}/api/services/app/Hangfire"
|
|
10
|
+
|
|
11
|
+
def sync_doi(self, id: str):
|
|
12
|
+
"""Trigger a DOI synchronization task."""
|
|
13
|
+
url = f"{self.base_url}/TriggerProcessDigitalObjectIdentifier?id={id}"
|
|
14
|
+
|
|
15
|
+
response = post_data(url, headers=self.set_auth_headers())
|
|
16
|
+
|
|
17
|
+
if response.get('success') == True:
|
|
18
|
+
return response.get('result')
|
|
19
|
+
else:
|
|
20
|
+
raise ValueError(extract_api_error(response))
|
|
21
|
+
|
|
22
|
+
def get_recurring_jobs(self) -> list:
|
|
23
|
+
"""List the recurring Hangfire jobs registered on the server.
|
|
24
|
+
|
|
25
|
+
The worker registers them; the API reads the same Hangfire storage.
|
|
26
|
+
Requires the Hangfire dashboard permission
|
|
27
|
+
(``Pages.Administration.HangfireDashboard``).
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
list[dict]: One dict per job with ``id``, ``cron``, ``queue``,
|
|
31
|
+
``timeZoneId``, ``job`` (``Type.Method``), ``nextExecution``,
|
|
32
|
+
``lastExecution``, ``lastJobId``, ``lastJobState``,
|
|
33
|
+
``createdAt`` and ``error``. Timestamps are UTC.
|
|
34
|
+
"""
|
|
35
|
+
url = f"{self.base_url}/GetRecurringJobs"
|
|
36
|
+
|
|
37
|
+
response = get_data(url, headers=self.set_auth_headers())
|
|
38
|
+
|
|
39
|
+
if response.get('success') == True:
|
|
40
|
+
result = response.get('result') or {}
|
|
41
|
+
items = result.get('items') if isinstance(result, dict) else result
|
|
42
|
+
return items or []
|
|
43
|
+
raise self._recurring_error(response, "Could not list the recurring jobs")
|
|
44
|
+
|
|
45
|
+
def find_recurring_job(self, id: str) -> dict:
|
|
46
|
+
"""Return the recurring job with this id (case-insensitive).
|
|
47
|
+
|
|
48
|
+
Raises:
|
|
49
|
+
ValueError: If no job has that id; the message lists the valid ids.
|
|
50
|
+
"""
|
|
51
|
+
wanted = str(id or "").strip()
|
|
52
|
+
if not wanted:
|
|
53
|
+
raise ValueError("A recurring job id is required. Run 'das hangfire list' to see the ids.")
|
|
54
|
+
|
|
55
|
+
jobs = self.get_recurring_jobs()
|
|
56
|
+
for job in jobs:
|
|
57
|
+
if job.get('id') == wanted:
|
|
58
|
+
return job
|
|
59
|
+
for job in jobs:
|
|
60
|
+
if str(job.get('id') or "").lower() == wanted.lower():
|
|
61
|
+
return job
|
|
62
|
+
|
|
63
|
+
available = "\n".join(f" • {job.get('id')}" for job in jobs) or " (none)"
|
|
64
|
+
raise ValueError(f"Recurring job '{wanted}' was not found. Available recurring jobs:\n{available}")
|
|
65
|
+
|
|
66
|
+
def trigger_recurring_job(self, id: str) -> dict:
|
|
67
|
+
"""Enqueue one immediate run of a recurring job ("Trigger now").
|
|
68
|
+
|
|
69
|
+
The schedule is left untouched. Requires the Hangfire dashboard
|
|
70
|
+
permission (``Pages.Administration.HangfireDashboard``).
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
id (str): The recurring job id, as listed by :meth:`get_recurring_jobs`.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
dict: ``{"id": <recurring job id>, "jobId": <enqueued background job id>}``.
|
|
77
|
+
"""
|
|
78
|
+
if id is None or not str(id).strip():
|
|
79
|
+
raise ValueError("A recurring job id is required. Run 'das hangfire list' to see the ids.")
|
|
80
|
+
|
|
81
|
+
url = f"{self.base_url}/TriggerRecurringJob"
|
|
82
|
+
|
|
83
|
+
response = post_data(url, headers=self.set_auth_headers(), data={"id": str(id).strip()})
|
|
84
|
+
|
|
85
|
+
if response.get('success') == True:
|
|
86
|
+
return response.get('result') or {}
|
|
87
|
+
raise self._recurring_error(response, f"Could not trigger recurring job '{id}'")
|
|
88
|
+
|
|
89
|
+
@staticmethod
|
|
90
|
+
def _recurring_error(response, default):
|
|
91
|
+
error = build_api_error(response, default=default)
|
|
92
|
+
# A 404 here means the route itself is missing: the server predates the
|
|
93
|
+
# recurring-job endpoints. (An unknown job id is reported by message.)
|
|
94
|
+
if isinstance(error, DasNotFoundError):
|
|
95
|
+
return DasNotFoundError(
|
|
96
|
+
"This DAS server does not expose recurring Hangfire jobs yet; "
|
|
97
|
+
"it needs a newer version of the DAS API.",
|
|
98
|
+
status_code=error.status_code,
|
|
99
|
+
correlation_id=error.correlation_id,
|
|
100
|
+
)
|
|
101
|
+
return error
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: das-cli
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.9.0
|
|
4
4
|
Summary: DAS api client.
|
|
5
5
|
Author: Royal Netherlands Institute for Sea Research
|
|
6
6
|
License-Expression: MIT
|
|
@@ -301,6 +301,12 @@ das cache list
|
|
|
301
301
|
das cache clear "attributes"
|
|
302
302
|
das cache clear-all
|
|
303
303
|
|
|
304
|
+
# Hangfire (background jobs) — needs the Hangfire dashboard permission
|
|
305
|
+
das hangfire list # recurring jobs: ID, cron, queue, last/next run
|
|
306
|
+
das hangfire list --format json
|
|
307
|
+
das hangfire trigger "5. harvest-archive" # run a recurring job now (quote IDs with spaces)
|
|
308
|
+
das hangfire sync-doi <entry-id>
|
|
309
|
+
|
|
304
310
|
# Config
|
|
305
311
|
das config ssl-verify true
|
|
306
312
|
das config ssl-status
|
|
@@ -407,6 +413,34 @@ if info["status"] == "valid":
|
|
|
407
413
|
`get_current_user()` and `validate_api_key(key)` — the last one checks a key
|
|
408
414
|
without storing it.
|
|
409
415
|
|
|
416
|
+
### Recurring Hangfire jobs
|
|
417
|
+
|
|
418
|
+
Every recurring job the DAS worker registers can be listed and run on demand —
|
|
419
|
+
the equivalent of *Trigger now* in the `/hangfire` dashboard. Triggering
|
|
420
|
+
enqueues one extra run; the job's schedule is not changed. Your account needs
|
|
421
|
+
the **Hangfire dashboard** permission (`Pages.Administration.HangfireDashboard`).
|
|
422
|
+
|
|
423
|
+
```python
|
|
424
|
+
from das.app import Das
|
|
425
|
+
|
|
426
|
+
das = Das() # uses the URL + credential saved by `das login`
|
|
427
|
+
|
|
428
|
+
for job in das.hangfire.get_recurring_jobs():
|
|
429
|
+
print(job["id"], job["cron"], job["queue"], job["nextExecution"], job["lastJobState"])
|
|
430
|
+
|
|
431
|
+
result = das.hangfire.trigger_recurring_job("5. harvest-archive")
|
|
432
|
+
print(result["jobId"]) # id of the background job that was enqueued
|
|
433
|
+
|
|
434
|
+
# Case-insensitive lookup; raises ValueError listing the valid ids when unknown
|
|
435
|
+
job = das.hangfire.find_recurring_job("system health check")
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
Each job is a dict with `id`, `cron`, `queue`, `timeZoneId`, `job`
|
|
439
|
+
(`Type.Method`), `nextExecution`, `lastExecution`, `lastJobId`, `lastJobState`,
|
|
440
|
+
`createdAt` and `error`; timestamps are UTC. Failures raise a `DasApiError`
|
|
441
|
+
subclass (e.g. `DasPermissionError` without the permission, `DasNotFoundError`
|
|
442
|
+
when the server is too old to have these endpoints).
|
|
443
|
+
|
|
410
444
|
## Manager Layer API Reference (Domain Layer)
|
|
411
445
|
|
|
412
446
|
Managers are the recommended Python API. They translate user-friendly field names, codes, and query syntax into the lower-level DAS API calls.
|
|
@@ -511,6 +545,11 @@ result = entries.create(attribute="Cores", entry={
|
|
|
511
545
|
# result -> [{"id": "<guid>", "code": "zb.b.xxx", "status": "success"}]
|
|
512
546
|
new_id = result[0]["id"]
|
|
513
547
|
|
|
548
|
+
# The code is generated by the server and read back with a second request.
|
|
549
|
+
# Skip that request when only the id is needed (imports, benchmarks):
|
|
550
|
+
result = entries.create(attribute="Cores", entry={...}, fetch_code=False)
|
|
551
|
+
# result -> [{"id": "<guid>", "status": "success"}]
|
|
552
|
+
|
|
514
553
|
# Bulk create
|
|
515
554
|
results = entries.create(attribute="Cores", entries=[
|
|
516
555
|
{"Alias": "bulk.001", "Event": "64PE428-02PC", "Number": 1},
|
|
@@ -529,6 +568,28 @@ entries.create(attribute="Cruise", entry={
|
|
|
529
568
|
})
|
|
530
569
|
```
|
|
531
570
|
|
|
571
|
+
#### `warm_select_cache` — pre-resolve select values before an import
|
|
572
|
+
|
|
573
|
+
Every select field value (`"Event": "64PE428-02PC"`, `"Device": "CTD"`) is
|
|
574
|
+
resolved with one search request the first time the manager sees it. An
|
|
575
|
+
import that references many different stations, devices or cruises pays one
|
|
576
|
+
request per distinct value. `warm_select_cache` loads the options of every
|
|
577
|
+
select field of an attribute up front and caches them by code, display name
|
|
578
|
+
and id, so the rows that follow resolve without a request:
|
|
579
|
+
|
|
580
|
+
```python
|
|
581
|
+
entries = EntryManager()
|
|
582
|
+
cached = entries.warm_select_cache("Event") # one request per select field (per 1000 options)
|
|
583
|
+
print(f"{cached} select options cached")
|
|
584
|
+
|
|
585
|
+
for row in rows:
|
|
586
|
+
entries.create(attribute="Event", entry=row, fetch_code=False) # one request per row
|
|
587
|
+
```
|
|
588
|
+
|
|
589
|
+
Values must match the server's spelling and case; anything else still falls
|
|
590
|
+
back to a search. Fields with more than `max_results` options (default 1000)
|
|
591
|
+
are warmed partially. The cache lives as long as the manager instance.
|
|
592
|
+
|
|
532
593
|
#### `update` — update one or many entries
|
|
533
594
|
|
|
534
595
|
```python
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
from das.common.api import post_data
|
|
2
|
-
from das.common.errors import extract_api_error
|
|
3
|
-
from das.services.service_base import ServiceBase
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
class HangfireService(ServiceBase):
|
|
7
|
-
def __init__(self, base_url):
|
|
8
|
-
self.base_url = f"{base_url}/api/services/app/Hangfire"
|
|
9
|
-
|
|
10
|
-
def sync_doi(self, id: str):
|
|
11
|
-
"""Trigger a DOI synchronization task."""
|
|
12
|
-
url = f"{self.base_url}/TriggerProcessDigitalObjectIdentifier?id={id}"
|
|
13
|
-
|
|
14
|
-
response = post_data(url, headers=self.set_auth_headers())
|
|
15
|
-
|
|
16
|
-
if response.get('success') == True:
|
|
17
|
-
return response.get('result')
|
|
18
|
-
else:
|
|
19
|
-
raise ValueError(extract_api_error(response))
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|