pacific-cli 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,53 @@
1
+ """Constants and settings for the Pacific CLI's document commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import timedelta
6
+
7
+ from pydantic import Field
8
+ from pydantic_settings import BaseSettings, SettingsConfigDict
9
+
10
+ from pacific_cli.config import PACIFIC_CLI_PUBLIC_API_PREFIX
11
+
12
+ PACIFIC_CLI_INGEST_PATH = f"{PACIFIC_CLI_PUBLIC_API_PREFIX}/ingest"
13
+ PACIFIC_CLI_BULK_INGEST_PATH = f"{PACIFIC_CLI_PUBLIC_API_PREFIX}/ingest/bulk"
14
+ PACIFIC_CLI_DOCUMENTS_PATH = f"{PACIFIC_CLI_PUBLIC_API_PREFIX}/documents"
15
+ PACIFIC_CLI_JOBS_PATH = f"{PACIFIC_CLI_PUBLIC_API_PREFIX}/jobs"
16
+
17
+ #: The multipart fields the ingest routes read (`public_ingest`, `public_bulk_ingest`).
18
+ PACIFIC_CLI_INGEST_FILE_FIELD = "file"
19
+ PACIFIC_CLI_BULK_INGEST_FILES_FIELD = "files"
20
+ PACIFIC_CLI_INGEST_METADATA_FIELD = "metadata"
21
+
22
+ #: ``--attr`` is ``KEY=VALUE``; a key repeated takes every value given.
23
+ PACIFIC_CLI_ATTRIBUTE_SEPARATOR = "="
24
+
25
+
26
+ class PacificCliDocumentSettings(BaseSettings):
27
+ """Tunables of uploading and waiting, as ``PACIFIC_CLI_*`` variables."""
28
+
29
+ model_config = SettingsConfigDict(
30
+ env_prefix="PACIFIC_CLI_", extra="ignore", env_ignore_empty=True
31
+ )
32
+
33
+ upload_batch_size: int = Field(
34
+ 100,
35
+ ge=1,
36
+ description="Files per bulk ingest call; the server's own cap "
37
+ "(PUBLIC_INGEST_BULK_MAX_FILES) is 100 unless its operator changed it",
38
+ )
39
+ documents_page_size: int = Field(
40
+ 200, ge=1, le=200, description="Documents per page when listing"
41
+ )
42
+ documents_list_limit: int = Field(
43
+ 50,
44
+ ge=1,
45
+ description="How many `documents list` shows without --limit or --all: "
46
+ "an organization can hold more than anyone wants to wait for",
47
+ )
48
+ job_poll_interval: timedelta = Field(
49
+ timedelta(seconds=2), description="Between polls of an ingest job"
50
+ )
51
+ job_wait_timeout: timedelta = Field(
52
+ timedelta(minutes=15), description="How long --wait waits for ingest jobs"
53
+ )
@@ -0,0 +1,213 @@
1
+ """Uploads with the metadata access policies match, the jobs they start, and the documents list."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import time
7
+ from collections.abc import Iterator, Sequence
8
+ from http import HTTPMethod
9
+ from pathlib import Path
10
+ from urllib.parse import quote
11
+
12
+ import httpx
13
+ from pydantic import ValidationError
14
+
15
+ from pacific_cli.auth.client import PacificCliApiClient
16
+ from pacific_cli.auth.types import (
17
+ PacificCliApiError,
18
+ PacificCliError,
19
+ PacificCliUploadPart,
20
+ )
21
+ from pacific_cli.documents.config import (
22
+ PACIFIC_CLI_ATTRIBUTE_SEPARATOR,
23
+ PACIFIC_CLI_BULK_INGEST_FILES_FIELD,
24
+ PACIFIC_CLI_BULK_INGEST_PATH,
25
+ PACIFIC_CLI_DOCUMENTS_PATH,
26
+ PACIFIC_CLI_INGEST_FILE_FIELD,
27
+ PACIFIC_CLI_INGEST_METADATA_FIELD,
28
+ PACIFIC_CLI_INGEST_PATH,
29
+ PACIFIC_CLI_JOBS_PATH,
30
+ PacificCliDocumentSettings,
31
+ )
32
+ from pacific_cli.documents.types import (
33
+ PacificCliBulkIngestReceipt,
34
+ PacificCliDocumentsPage,
35
+ PacificCliIngestReceipt,
36
+ PacificCliIngestStage,
37
+ PacificCliJob,
38
+ PacificCliJobId,
39
+ PacificCliJobStatus,
40
+ PacificCliUploadAttributes,
41
+ PacificCliUploadMetadata,
42
+ PacificCliUploadStarted,
43
+ )
44
+
45
+
46
+ class PacificCliDocumentService:
47
+ """Uploads files, waits for them to become searchable, and lists what the caller can read."""
48
+
49
+ def __init__(
50
+ self, client: PacificCliApiClient, *, settings: PacificCliDocumentSettings
51
+ ) -> None:
52
+ self._client = client
53
+ self._settings = settings
54
+
55
+ @staticmethod
56
+ def metadata(
57
+ *, labels: Sequence[str], attributes: Sequence[str]
58
+ ) -> PacificCliUploadMetadata:
59
+ """The upload's metadata from ``--label`` and ``--attr KEY=VALUE`` options.
60
+
61
+ A malformed option is refused before any file is sent; the server's caps
62
+ on how many keys and values a document holds are the server's to enforce.
63
+ """
64
+ given = []
65
+ for text in attributes:
66
+ key, separator, value = text.partition(PACIFIC_CLI_ATTRIBUTE_SEPARATOR)
67
+ if not separator or not key.strip():
68
+ raise PacificCliError(f"--attr takes KEY=VALUE; got {text!r}")
69
+ given.append((key.strip(), value))
70
+ # A key given twice keeps both values, in the order given.
71
+ keys = dict.fromkeys(key for key, _value in given)
72
+ try:
73
+ return PacificCliUploadMetadata(
74
+ labels=list(labels),
75
+ attributes=PacificCliUploadAttributes(
76
+ {
77
+ key: [value for name, value in given if name == key]
78
+ for key in keys
79
+ }
80
+ ),
81
+ )
82
+ except ValidationError as exc:
83
+ problems = "; ".join(error["msg"] for error in exc.errors())
84
+ raise PacificCliError(f"The metadata would be refused: {problems}") from exc
85
+
86
+ def upload(
87
+ self, paths: Sequence[Path], *, metadata: PacificCliUploadMetadata
88
+ ) -> list[PacificCliUploadStarted]:
89
+ """Send the files with one set of metadata; every file is labelled alike.
90
+
91
+ One file goes to ``/ingest``, whose refusal names the file's problem;
92
+ more go to ``/ingest/bulk`` in batches, each accepted whole or not at all.
93
+ """
94
+ missing = [str(path) for path in paths if not path.is_file()]
95
+ if missing:
96
+ raise PacificCliError(f"Not a file: {', '.join(missing)}")
97
+ form = {PACIFIC_CLI_INGEST_METADATA_FIELD: metadata.model_dump_json()}
98
+ if len(paths) == 1:
99
+ (path,) = paths
100
+ response = self._client.request(
101
+ HTTPMethod.POST,
102
+ path=PACIFIC_CLI_INGEST_PATH,
103
+ form=form,
104
+ files=[
105
+ PacificCliUploadPart(field=PACIFIC_CLI_INGEST_FILE_FIELD, path=path)
106
+ ],
107
+ )
108
+ receipt = PacificCliIngestReceipt.model_validate_json(response.content)
109
+ return [PacificCliUploadStarted(file_name=path.name, job_id=receipt.job_id)]
110
+ started: list[PacificCliUploadStarted] = []
111
+ for batch in itertools.batched(paths, self._settings.upload_batch_size):
112
+ try:
113
+ response = self._client.request(
114
+ HTTPMethod.POST,
115
+ path=PACIFIC_CLI_BULK_INGEST_PATH,
116
+ form=form,
117
+ files=[
118
+ PacificCliUploadPart(
119
+ field=PACIFIC_CLI_BULK_INGEST_FILES_FIELD, path=path
120
+ )
121
+ for path in batch
122
+ ],
123
+ )
124
+ except (PacificCliApiError, httpx.TransportError) as exc:
125
+ # A refusal and a dropped connection alike: the earlier batches'
126
+ # jobs are running, and a retry of the whole command would
127
+ # upload those files a second time.
128
+ if not started:
129
+ raise
130
+ reason = (
131
+ exc.message
132
+ if isinstance(exc, PacificCliApiError)
133
+ else f"Could not reach {exc.request.url}: {exc}"
134
+ )
135
+ accepted = ", ".join(
136
+ f"{item.file_name} ({item.job_id})" for item in started
137
+ )
138
+ raise PacificCliError(
139
+ f"{reason}\nAlready accepted from earlier batches: {accepted}"
140
+ ) from exc
141
+ started.extend(
142
+ PacificCliUploadStarted(file_name=item.file_name, job_id=item.job_id)
143
+ for item in PacificCliBulkIngestReceipt.model_validate_json(
144
+ response.content
145
+ ).data
146
+ )
147
+ return started
148
+
149
+ def job(self, job_id: PacificCliJobId) -> PacificCliJob:
150
+ return self._client.parsed(
151
+ PacificCliJob,
152
+ method=HTTPMethod.GET,
153
+ path=f"{PACIFIC_CLI_JOBS_PATH}/{quote(job_id, safe='')}",
154
+ )
155
+
156
+ def wait_until_searchable(
157
+ self, job_ids: Sequence[PacificCliJobId]
158
+ ) -> list[PacificCliJob]:
159
+ """Poll each job until its document is searchable, or the job has stopped.
160
+
161
+ Searchable is what a policy test needs; extraction can run on for minutes
162
+ after it, so waiting for ``completed`` would hold the terminal for nothing.
163
+ """
164
+ deadline = time.monotonic() + self._settings.job_wait_timeout.total_seconds()
165
+ settled: dict[PacificCliJobId, PacificCliJob] = {}
166
+ while True:
167
+ for job_id in job_ids:
168
+ if job_id in settled:
169
+ continue
170
+ job = self.job(job_id)
171
+ if job.status is not PacificCliJobStatus.RUNNING or job.stage in (
172
+ PacificCliIngestStage.SEARCHABLE,
173
+ PacificCliIngestStage.COMPLETED,
174
+ ):
175
+ settled[job_id] = job
176
+ if len(settled) == len(job_ids):
177
+ return [settled[job_id] for job_id in job_ids]
178
+ if time.monotonic() >= deadline:
179
+ raise PacificCliError(
180
+ f"{len(job_ids) - len(settled)} job(s) not searchable after "
181
+ f"{self._settings.job_wait_timeout}; check one with "
182
+ "`pacific documents job JOB_ID`"
183
+ )
184
+ time.sleep(self._settings.job_poll_interval.total_seconds())
185
+
186
+ def document_pages(self, *, limit: int | None) -> Iterator[PacificCliDocumentsPage]:
187
+ """Pages of the documents the caller can read, newest first: ``limit`` in all, or every one.
188
+
189
+ Each request asks for no more than is still wanted, so a short listing of
190
+ a large organization reads one small page; the last page's ``has_more``
191
+ says whether the listing stopped short of the end.
192
+ """
193
+ cursor: str | None = None
194
+ remaining = limit
195
+ while remaining is None or remaining > 0:
196
+ size = self._settings.documents_page_size
197
+ params: dict[str, str | int | bool] = {
198
+ "limit": size if remaining is None else min(remaining, size)
199
+ }
200
+ if cursor is not None:
201
+ params["cursor"] = cursor
202
+ page = self._client.parsed(
203
+ PacificCliDocumentsPage,
204
+ method=HTTPMethod.GET,
205
+ path=PACIFIC_CLI_DOCUMENTS_PATH,
206
+ params=params,
207
+ )
208
+ yield page
209
+ if not page.has_more:
210
+ return
211
+ if remaining is not None:
212
+ remaining -= len(page.data)
213
+ cursor = page.next_cursor
@@ -0,0 +1,176 @@
1
+ """What the CLI sends to and reads from the ingest, jobs and documents routes.
2
+
3
+ Each model names only the members the CLI uses and ignores the rest, so the
4
+ server can add fields freely; ``contract_test.py`` holds each one to the schema
5
+ of the same name in ``docs/api/public_api_openapi.json``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from enum import StrEnum
11
+ from typing import Annotated, NewType
12
+
13
+ from pydantic import (
14
+ BaseModel,
15
+ ConfigDict,
16
+ Field,
17
+ RootModel,
18
+ StringConstraints,
19
+ field_validator,
20
+ )
21
+
22
+ #: An ingest job's opaque handle: a string the server says not to parse.
23
+ PacificCliJobId = NewType("PacificCliJobId", str)
24
+
25
+ #: A label as policies match it: trimmed and lower-cased, as the server stores it.
26
+ PacificCliLabel = Annotated[
27
+ str, StringConstraints(strip_whitespace=True, to_lower=True, min_length=1)
28
+ ]
29
+ PacificCliAttributeValue = Annotated[
30
+ str, StringConstraints(strip_whitespace=True, min_length=1)
31
+ ]
32
+
33
+
34
+ class PacificCliJobStatus(StrEnum):
35
+ """``PublicJobStatus``: where a job is."""
36
+
37
+ RUNNING = "running"
38
+ COMPLETED = "completed"
39
+ FAILED = "failed"
40
+ CANCELLED = "cancelled"
41
+ NOT_STARTED = "not_started"
42
+
43
+ @property
44
+ def stopped_short(self) -> bool:
45
+ """The job ended without its document becoming searchable."""
46
+ match self:
47
+ case PacificCliJobStatus.FAILED | PacificCliJobStatus.CANCELLED:
48
+ return True
49
+ case (
50
+ PacificCliJobStatus.RUNNING
51
+ | PacificCliJobStatus.COMPLETED
52
+ | PacificCliJobStatus.NOT_STARTED
53
+ ):
54
+ return False
55
+
56
+
57
+ class PacificCliIngestStage(StrEnum):
58
+ """``DocumentIngestStage``: how far an ingest has carried its document."""
59
+
60
+ RECEIVED = "received"
61
+ SEARCHABLE = "searchable"
62
+ COMPLETED = "completed"
63
+
64
+
65
+ class PacificCliUploadAttributes(RootModel[dict[str, list[PacificCliAttributeValue]]]):
66
+ """Custom keys on an upload, each with one or more values (``resource.metadata.<key>``)."""
67
+
68
+ root: dict[str, list[PacificCliAttributeValue]] = Field(
69
+ default_factory=dict, description="Each key with its values"
70
+ )
71
+
72
+
73
+ class PacificCliUploadMetadata(BaseModel):
74
+ """The ``metadata`` form field of an ingest: what access policies match on the document.
75
+
76
+ The server owns the limits (how many keys, values and labels) and refuses a
77
+ call past one with a 422 the CLI prints; this checks only the shape.
78
+ """
79
+
80
+ model_config = ConfigDict(frozen=True, extra="forbid")
81
+
82
+ labels: list[PacificCliLabel] = Field(
83
+ default_factory=list, description="Matched as resource.metadata.labels"
84
+ )
85
+ attributes: PacificCliUploadAttributes = Field(
86
+ default_factory=PacificCliUploadAttributes,
87
+ description="Matched as resource.metadata.<key>",
88
+ )
89
+
90
+ @field_validator("labels")
91
+ @classmethod
92
+ def _dedupe_labels(cls, labels: list[str]) -> list[str]:
93
+ return list(dict.fromkeys(labels))
94
+
95
+
96
+ class PacificCliIngestReceipt(BaseModel):
97
+ """``PublicIngestResponse``: the job that processes the file."""
98
+
99
+ model_config = ConfigDict(frozen=True, extra="ignore")
100
+
101
+ job_id: PacificCliJobId = Field(
102
+ ..., description="Poll it at /public/v1/jobs/{job_id}"
103
+ )
104
+
105
+
106
+ class PacificCliBulkIngestFile(BaseModel):
107
+ """``PublicBulkIngestFile``: one accepted file of a bulk ingest."""
108
+
109
+ model_config = ConfigDict(frozen=True, extra="ignore")
110
+
111
+ file_name: str = Field(..., description="The file name as sent")
112
+ job_id: PacificCliJobId = Field(..., description="This file's ingestion job")
113
+
114
+
115
+ class PacificCliBulkIngestReceipt(BaseModel):
116
+ """``PublicBulkIngestResponse``: one job per file, in the order sent."""
117
+
118
+ model_config = ConfigDict(frozen=True, extra="ignore")
119
+
120
+ data: list[PacificCliBulkIngestFile] = Field(..., description="One per file")
121
+
122
+
123
+ class PacificCliJob(BaseModel):
124
+ """``PublicJob``: where an ingest job is."""
125
+
126
+ model_config = ConfigDict(frozen=True, extra="ignore")
127
+
128
+ job_id: PacificCliJobId = Field(..., description="The job's handle")
129
+ status: PacificCliJobStatus = Field(..., description="Where the job is")
130
+ stage: PacificCliIngestStage | None = Field(
131
+ None, description="received, searchable, completed"
132
+ )
133
+ resource_id: int | None = Field(
134
+ None, description="The document id, once there is one"
135
+ )
136
+ error: str | None = Field(None, description="Why it failed")
137
+
138
+
139
+ class PacificCliDocumentMetadata(BaseModel):
140
+ """``PublicDocumentMetadata``: what a policy matches on a listed document."""
141
+
142
+ model_config = ConfigDict(frozen=True, extra="ignore")
143
+
144
+ labels: list[str] = Field(
145
+ default_factory=list, description="resource.metadata.labels"
146
+ )
147
+
148
+
149
+ class PacificCliDocument(BaseModel):
150
+ """``PublicDocument``: one document the caller can read."""
151
+
152
+ model_config = ConfigDict(frozen=True, extra="ignore")
153
+
154
+ document_id: int = Field(..., description="The document id")
155
+ file_name: str | None = Field(None, description="Its file name")
156
+ source: str = Field(..., description="Where it came from, such as Upload")
157
+ metadata: PacificCliDocumentMetadata = Field(..., description="What policies match")
158
+
159
+
160
+ class PacificCliDocumentsPage(BaseModel):
161
+ """``PublicDocumentsPage``: one page of the documents list."""
162
+
163
+ model_config = ConfigDict(frozen=True, extra="ignore")
164
+
165
+ data: list[PacificCliDocument] = Field(..., description="The documents")
166
+ has_more: bool = Field(..., description="Whether to ask for another page")
167
+ next_cursor: str = Field(..., description="Pass back as `cursor`")
168
+
169
+
170
+ class PacificCliUploadStarted(BaseModel):
171
+ """One file the server accepted, and the job processing it."""
172
+
173
+ model_config = ConfigDict(frozen=True, extra="forbid")
174
+
175
+ file_name: str = Field(..., description="The file as sent")
176
+ job_id: PacificCliJobId = Field(..., description="Its ingestion job")
@@ -0,0 +1 @@
1
+ """Creating, listing and revoking API keys from a browser sign-in."""
@@ -0,0 +1,117 @@
1
+ """``pacific keys``: create, list and revoke your API keys."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import webbrowser
6
+
7
+ import click
8
+ from rich.console import Console
9
+ from rich.table import Table
10
+
11
+ from pacific_cli.auth.runtime import PacificCliRuntime
12
+ from pacific_cli.keys.service import PacificCliKeyService
13
+ from pacific_cli.keys.types import PacificCliKeyId, PacificCliKeyLifetime
14
+
15
+ _LIFETIMES = click.Choice([lifetime.value for lifetime in PacificCliKeyLifetime])
16
+
17
+
18
+ def _service(runtime: PacificCliRuntime) -> PacificCliKeyService:
19
+ def show(*, url: str) -> None:
20
+ click.echo(f"Sign in at:\n\n {url}\n", err=True)
21
+ if not webbrowser.open(url):
22
+ click.echo("Could not open a browser; open the link above.", err=True)
23
+
24
+ return PacificCliKeyService(
25
+ runtime, open_browser=show, notify=lambda message: click.echo(message, err=True)
26
+ )
27
+
28
+
29
+ def _expiry(value: object) -> str:
30
+ return "never" if value is None else str(value)
31
+
32
+
33
+ @click.group("keys")
34
+ def keys_group() -> None:
35
+ """Your own API keys: create them for scripts and CI, list and revoke them.
36
+
37
+ Keys are managed from a browser sign-in that asked for keys:manage (never
38
+ with a key). If this profile's sign-in did not ask, or is too old to create
39
+ a key, the command signs you in once more and revokes that sign-in after.
40
+ """
41
+
42
+
43
+ @keys_group.command("list")
44
+ @click.option("--json", "as_json", is_flag=True, help="Print JSON")
45
+ @click.pass_obj
46
+ def keys_list(runtime: PacificCliRuntime, as_json: bool) -> None:
47
+ """Your keys, without their values."""
48
+ keys = _service(runtime).list_keys()
49
+ if as_json:
50
+ click.echo(keys.model_dump_json(indent=2))
51
+ return
52
+ table = Table("id", "name", "prefix", "scopes", "expires", box=None)
53
+ for key in keys.data:
54
+ table.add_row(
55
+ key.key_id,
56
+ key.name or "",
57
+ key.token_prefix,
58
+ ", ".join(key.scopes),
59
+ _expiry(key.expires_at),
60
+ )
61
+ Console().print(table)
62
+
63
+
64
+ @keys_group.command("create")
65
+ @click.option(
66
+ "--scope",
67
+ "-s",
68
+ "scopes",
69
+ multiple=True,
70
+ required=True,
71
+ metavar="SCOPE",
72
+ help="What the key may do, such as documents:write (repeatable)",
73
+ )
74
+ @click.option("--name", help="A label, shown in the list")
75
+ @click.option(
76
+ "--expires",
77
+ type=_LIFETIMES,
78
+ default=PacificCliKeyLifetime.THIRTY_DAYS.value,
79
+ show_default=True,
80
+ help="How long the key lasts",
81
+ )
82
+ @click.option("--json", "as_json", is_flag=True, help="Print JSON")
83
+ @click.pass_obj
84
+ def keys_create(
85
+ runtime: PacificCliRuntime,
86
+ scopes: tuple[str, ...],
87
+ name: str | None,
88
+ expires: str,
89
+ as_json: bool,
90
+ ) -> None:
91
+ """Create a key for yourself; its value is printed once.
92
+
93
+ \b
94
+ pacific keys create -s documents:write -s tools:read --name "CI deploy" --expires 90d
95
+ """
96
+ key = _service(runtime).create_key(
97
+ scopes=scopes, name=name, lifetime=PacificCliKeyLifetime(expires)
98
+ )
99
+ if as_json:
100
+ click.echo(key.model_dump_json(indent=2))
101
+ return
102
+ click.echo(key.token)
103
+ click.echo(
104
+ f"\nKey {key.key_id} ({', '.join(key.scopes)}), expires {_expiry(key.expires_at)}. "
105
+ "This is the only time its value is shown. To use it from a profile:\n"
106
+ " pacific profile add NAME --base-url URL && pacific -p NAME auth set-key --stdin",
107
+ err=True,
108
+ )
109
+
110
+
111
+ @keys_group.command("revoke")
112
+ @click.argument("key_id")
113
+ @click.pass_obj
114
+ def keys_revoke(runtime: PacificCliRuntime, key_id: str) -> None:
115
+ """Revoke one of your keys. Calls already using it may succeed for up to a minute."""
116
+ _service(runtime).revoke_key(PacificCliKeyId(key_id))
117
+ click.echo(f"Revoked {key_id}")
@@ -0,0 +1,11 @@
1
+ """Constants for the Pacific CLI's key commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pacific_cli.config import PACIFIC_CLI_PUBLIC_API_PREFIX
6
+
7
+ PACIFIC_CLI_KEYS_PATH = f"{PACIFIC_CLI_PUBLIC_API_PREFIX}/keys"
8
+
9
+ #: The scope a sign-in names to manage keys. Full access does not imply it, so
10
+ #: a one-off sign-in asks for it and nothing else (the member's full access).
11
+ PACIFIC_CLI_KEY_MANAGEMENT_SCOPE = "keys:manage"