Repository navigation
Expand file tree
/
Copy pathsdk_rb_gen.py
More file actions
292 lines (255 loc) · 11.4 KB
/
Copy pathsdk_rb_gen.py
File metadata and controls
292 lines (255 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
"""Generate the Ruby SDK's operation table, its per-op methods and its error classes
from the server's registry (the twins are sdk_py_client_gen.py and sdk_ts_gen.py).
Two files under `sdk/ruby/lib/clickhouse/loom/generated/`:
- `ops.rb`: `OPS`, one `OpSpec` per served op (idempotency, read-only, role,
maturity, the input's field names and the required ones), and one class per op
group with one method per op. `client.<group>.<method>(**fields)` posts
`/v1/<group>.<rest>`: the group is the op name's first segment and the method is
the rest with `.` turned into `_`, as in the Python SDK (`tracker.source.add` →
`client.tracker.source_add`). A method that would shadow a method every Ruby
object has takes a trailing underscore (`memory.inspect` → `memory.inspect_`).
- `errors.rb`: one `Error` subclass per server error code (`PINNED_CONFLICT` →
`ClickHouse::Loom::PinnedConflict`), from the same sources as the errors
reference (`docs_reference.py`), and `ERROR_CLASSES`, the code → class map
`Error.from_response` reads.
So a new server op or error code reaches the Ruby SDK by regeneration alone.
python scripts/codegen/sdk_rb_gen.py # write the files
python scripts/codegen/sdk_rb_gen.py --check # exit 1 when a file is stale (CI)
"""
from __future__ import annotations
import argparse
import json
import sys
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path: # run as a file
sys.path.insert(0, str(ROOT))
from scripts.codegen.common import GeneratedFile, OpFacts, pascal # noqa: E402
COMMAND = "python scripts/codegen/sdk_rb_gen.py"
OUT_DIR = ROOT / "sdk" / "ruby" / "lib" / "clickhouse" / "loom" / "generated"
HEADER = (
"# frozen_string_literal: true\n"
"\n"
"# GENERATED by scripts/codegen/sdk_rb_gen.py from {source} — do not edit.\n"
f"# Regenerate: {COMMAND} (CI: --check)\n"
)
#: The public methods of every Ruby object (`Object.public_instance_methods` on
#: Ruby 3.1 to 3.3). A generated method of one of these names would shadow it, so
#: irb or a test failure printing a group would make an HTTP call.
RUBY_OBJECT_METHODS = frozenset(
"__id__ __send__ class clone define_singleton_method display dup enum_for eql? equal? "
"extend freeze frozen? hash inspect instance_eval instance_exec instance_of? "
"instance_variable_defined? instance_variable_get instance_variable_set "
"instance_variables is_a? itself kind_of? method methods nil? object_id private_methods "
"protected_methods public_method public_methods public_send remove_instance_variable "
"respond_to? send singleton_class singleton_method singleton_methods tap then to_enum "
"to_s yield_self".split()
)
#: Methods the client defines by hand. A group of one of these names would be
#: hidden behind it; `search` is the one the client resolves itself (`client.search`
#: with no query is the `search.*` group).
CLIENT_METHODS = frozenset(
{"base_url", "call", "delete", "get", "identity", "op_group", "retry_policy", "set"}
)
#: Constants `ClickHouse::Loom` defines by hand, and the top-level ones its code names
#: unqualified (`Timeout::Error`, `JSON.parse`, ...): an error class of one of these
#: names would hide it inside the module, so it takes an `Error` suffix instead.
RESERVED_CONSTANTS = frozenset(
{
"CATEGORIES",
"Client",
"Configuration",
"DeleteResult",
"Error",
"Generated",
"Memory",
"OpGroup",
"OpSpec",
"RetryAfter",
"RetryPolicy",
"SearchHit",
"SearchResult",
"SetResult",
# top-level constants the hand-written code uses unqualified
"DidYouMean",
"Errno",
"Float",
"IOError",
"JSON",
"Net",
"OpenSSL",
"SecureRandom",
"SocketError",
"Struct",
"Time",
"Timeout",
"URI",
}
)
#: The keyword a generated method takes its transport options under
#: (`idempotency_key:`, `retry_policy:`); no op may have a field of this name.
OPTIONS_KEYWORD = "request_options"
def split_op(name: str) -> tuple[str, str]:
"""`tracker.source.add` → (`tracker`, `source_add`); `memory.inspect` → (`memory`,
`inspect_`)."""
group, _, rest = name.partition(".")
method = rest.replace(".", "_")
if method in RUBY_OBJECT_METHODS:
method += "_"
if not (group.isidentifier() and method.isidentifier() and group.islower()):
raise SystemExit(f"op {name!r} has no valid Ruby method name")
if group in RUBY_OBJECT_METHODS or group in CLIENT_METHODS:
raise SystemExit(f"op group {group!r} would shadow a method of the Ruby client")
return group, method
def _words(values: list[str]) -> str:
return "%w[" + " ".join(values) + "].freeze" if values else "[].freeze"
def _summary(schema: dict[str, object]) -> str:
text = str(schema.get("description") or "").strip().split("\n")[0]
return text if len(text) <= 160 else text[:157].rstrip() + "..."
def op_rows() -> list[tuple[OpFacts, list[str], list[str], str]]:
"""(facts, field names, required field names, summary) per served op, by name."""
from server.operations.registry import ALL_OPERATIONS
rows = []
for op in sorted(ALL_OPERATIONS, key=lambda o: o.name):
schema = op.input_model.model_json_schema()
fields = list(schema.get("properties") or {})
if OPTIONS_KEYWORD in fields:
raise SystemExit(f"op {op.name!r} has a field named {OPTIONS_KEYWORD!r}")
bad = [f for f in fields if not f.isidentifier()]
if bad:
raise SystemExit(
f"op {op.name!r} has fields that are not Ruby keyword arguments: {bad}"
)
required = [f for f in fields if f in set(schema.get("required") or [])]
rows.append((OpFacts.of(op), fields, required, _summary(schema)))
return rows
def build_ops() -> str:
rows = op_rows()
groups: dict[str, list[tuple[str, OpFacts, list[str], str]]] = defaultdict(list)
for facts, _fields, required, summary in rows:
group, method = split_op(facts.name)
if any(m == method for m, *_ in groups[group]):
raise SystemExit(f"two ops map to {group}.{method}")
groups[group].append((method, facts, required, summary))
out = [
HEADER.format(source="server.operations.registry.ALL_OPERATIONS"),
"module ClickHouse",
" module Loom",
" # Every served operation: its spec in OPS, and one method per op on the class",
" # of its group (`client.memory.set(...)` is `memory.set`).",
" module Generated",
f" OP_COUNT = {len(rows)}",
"",
" # The declared spec of every served op, by name; the HTTP path is /v1/<name>.",
" OPS = {",
]
for facts, fields, required, _summary in rows:
group, method = split_op(facts.name)
out.append(
f" {json.dumps(facts.name)} => OpSpec.new({json.dumps(facts.name)}, "
f"{json.dumps(group)}, {json.dumps(method)}, {str(facts.idempotent).lower()}, "
f"{str(facts.read_only).lower()}, {json.dumps(facts.role)}, "
f"{json.dumps(facts.maturity)}, {_words(fields)}, {_words(required)}),"
)
out += [" }.freeze", ""]
for group in sorted(groups):
out += _group_class(group, groups[group])
out += [" # The class of each op group, by name.", " GROUPS = {"]
out += [f" {json.dumps(g)} => {pascal(g)}Ops," for g in sorted(groups)]
out += [
" }.freeze",
"",
" # One accessor per op group on the client: `client.memory`, `client.task`, ...",
" module GroupAccessors",
]
for i, group in enumerate(sorted(groups)):
out += ([""] if i else []) + [
f" def {group}",
f" op_group({json.dumps(group)})",
" end",
]
out += [" end", " end", " end", "end"]
return "\n".join(out) + "\n"
def _group_class(group: str, ops: list[tuple[str, OpFacts, list[str], str]]) -> list[str]:
out = [f" # The `{group}.*` operations.", f" class {pascal(group)}Ops < OpGroup"]
for i, (method, facts, required, summary) in enumerate(ops):
traits = [facts.role, "read-only" if facts.read_only else "writes"]
if facts.idempotent and not facts.read_only:
traits.append("Idempotency-Key")
if facts.maturity != "stable":
traits.append(facts.maturity)
out += [""] if i else []
out.append(f" # `{facts.name}` ({', '.join(traits)}).")
if summary:
out.append(f" # {summary}")
if required:
out.append(f" # Required: {', '.join(required)}.")
out += [
f" def {method}(body = nil, {OPTIONS_KEYWORD}: nil, **fields)",
f" call_op({json.dumps(facts.name)}, body, fields, {OPTIONS_KEYWORD})",
" end",
]
return [*out, " end", ""]
def error_codes() -> list[tuple[str, str, int, str]]:
"""(code, class name, HTTP status or 0, summary) for every code the errors
reference lists, by code."""
from scripts.codegen.docs_reference import (
CLASS_BY_CODE,
_code_literals,
_typed_errors,
)
typed = _typed_errors()
codes = sorted({*typed, *_code_literals(), *CLASS_BY_CODE})
rows, taken = [], dict.fromkeys(RESERVED_CONSTANTS, "(hand-written)")
for code in codes:
name = pascal(code.lower())
if name in RESERVED_CONSTANTS:
name += "Error"
if not name.isidentifier() or not name[:1].isupper():
raise SystemExit(f"error code {code!r} has no valid Ruby class name")
if name in taken:
raise SystemExit(f"error codes {taken[name]!r} and {code!r} both map to {name}")
taken[name] = code
status, doc, _qual = typed.get(code, (0, "", ""))
rows.append((code, name, status, doc.strip().split("\n")[0]))
return rows
def build_errors() -> str:
rows = error_codes()
out = [
HEADER.format(source="the server's error codes (as docs/reference/errors.md)"),
"module ClickHouse",
" module Loom",
]
for code, name, status, doc in rows:
note = f"HTTP {status}. {doc}".strip() if status else "Server code"
out += [
f" # `{code}`: {note}",
f" class {name} < Error",
f" CODE = {json.dumps(code)}",
" end",
"",
]
out += [
f" # The Error subclass for each server code ({len(rows)} codes); a code not",
" # listed raises Error itself.",
" ERROR_CLASSES = {",
*[f" {json.dumps(code)} => {name}," for code, name, _s, _d in rows],
" }.freeze",
" end",
"end",
]
return "\n".join(out) + "\n"
TARGETS = (
(GeneratedFile(OUT_DIR / "ops.rb", COMMAND), build_ops),
(GeneratedFile(OUT_DIR / "errors.rb", COMMAND), build_errors),
)
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
ap.add_argument("--check", action="store_true", help="exit 1 when a file is stale")
args = ap.parse_args(argv)
return max(target.sync(build(), check=args.check) for target, build in TARGETS)
if __name__ == "__main__":
raise SystemExit(main())