fancy-google-sheets 0.1.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.
- fancy_google_sheets-0.1.0/.gitignore +24 -0
- fancy_google_sheets-0.1.0/CHANGELOG.md +74 -0
- fancy_google_sheets-0.1.0/LICENSE +21 -0
- fancy_google_sheets-0.1.0/PKG-INFO +73 -0
- fancy_google_sheets-0.1.0/README.md +51 -0
- fancy_google_sheets-0.1.0/pyproject.toml +87 -0
- fancy_google_sheets-0.1.0/src/fancy_google_sheets/__init__.py +37 -0
- fancy_google_sheets-0.1.0/src/fancy_google_sheets/_fake.py +170 -0
- fancy_google_sheets-0.1.0/src/fancy_google_sheets/_runtime.py +371 -0
- fancy_google_sheets-0.1.0/src/fancy_google_sheets/actions/__init__.py +14 -0
- fancy_google_sheets-0.1.0/src/fancy_google_sheets/actions/row_append.py +123 -0
- fancy_google_sheets-0.1.0/src/fancy_google_sheets/faker.py +62 -0
- fancy_google_sheets-0.1.0/src/fancy_google_sheets/py.typed +0 -0
- fancy_google_sheets-0.1.0/src/fancy_google_sheets/service.py +72 -0
- fancy_google_sheets-0.1.0/tests/test_faker.py +47 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
node_modules/
|
|
2
|
+
dist/
|
|
3
|
+
vendor/
|
|
4
|
+
.venv/
|
|
5
|
+
__pycache__/
|
|
6
|
+
*.egg-info/
|
|
7
|
+
.pytest_cache/
|
|
8
|
+
.ruff_cache/
|
|
9
|
+
.mypy_cache/
|
|
10
|
+
|
|
11
|
+
# Lockfiles are NOT source of a generated repo.
|
|
12
|
+
#
|
|
13
|
+
# The generator cannot emit one -- a lockfile is the result of a network
|
|
14
|
+
# resolve -- and "a provider repo must be generated and re-generatable" is the
|
|
15
|
+
# constraint the whole estate rests on. At a few hundred repos, a committed
|
|
16
|
+
# lockfile each is a few hundred files nothing can regenerate and a few hundred
|
|
17
|
+
# Dependabot surfaces.
|
|
18
|
+
#
|
|
19
|
+
# The trade is real and worth stating: CI resolves fresh on every run, so an
|
|
20
|
+
# upstream release inside the declared range can break a build with no change
|
|
21
|
+
# here. That is early warning rather than a surprise at publish time, and the
|
|
22
|
+
# ranges are deliberately narrow (>=X <2.0, never a caret on a 0.x).
|
|
23
|
+
composer.lock
|
|
24
|
+
package-lock.json
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@particle-academy/google-sheets-ui`,
|
|
4
|
+
`@particle-academy/google-sheets-js`, `particle-academy/google-sheets-php` and
|
|
5
|
+
`fancy-google-sheets`.
|
|
6
|
+
|
|
7
|
+
The four packages share one version, because they are generated from one
|
|
8
|
+
`provider/` definition and a version that meant something different in each
|
|
9
|
+
would be a version nobody could reason about.
|
|
10
|
+
|
|
11
|
+
## [0.1.0] — 2026-08-23
|
|
12
|
+
|
|
13
|
+
First release. Provider eight, and the first Google connector.
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- `row_append` — append a row to a sheet.
|
|
18
|
+
`POST /v4/spreadsheets/{spreadsheetId}/values/{range}:append`.
|
|
19
|
+
- A faker for it, so the node runs on a canvas with no Google account.
|
|
20
|
+
|
|
21
|
+
### Config can go in the URL now
|
|
22
|
+
|
|
23
|
+
Every provider before this one sent a fixed path. Google Sheets needs **two
|
|
24
|
+
config values in the URL** and one **in the query of a POST**, so where a value
|
|
25
|
+
lands is declarable — `send.in: "path" | "query" | "body"` — and stays derived
|
|
26
|
+
when unstated.
|
|
27
|
+
|
|
28
|
+
**A path value is URL-encoded, in all three runtimes.** A range is
|
|
29
|
+
`Sheet1!A:B`; it contains `!`, and a sheet named `Q1/Q2` contains a slash.
|
|
30
|
+
Interpolated raw it changes *which URL is called*, and Google answers 404 about
|
|
31
|
+
a spreadsheet rather than about encoding — pointing at the sheet name instead of
|
|
32
|
+
at the interpolation.
|
|
33
|
+
|
|
34
|
+
The path template and the config are checked against each other, the same way a
|
|
35
|
+
GraphQL document and its variables are: a placeholder nothing fills, a field
|
|
36
|
+
naming no placeholder, and an optional path field are all refused at definition
|
|
37
|
+
time. A URL cannot have a hole in it.
|
|
38
|
+
|
|
39
|
+
### `valueInputOption` is in the QUERY, and that is not cosmetic
|
|
40
|
+
|
|
41
|
+
Sent in the body, Google **ignores it silently** and falls back to `RAW`. An
|
|
42
|
+
author who asked for `USER_ENTERED` then gets `=SUM(A1:A2)` stored as text that
|
|
43
|
+
looks like a formula and never calculates. Nothing errors.
|
|
44
|
+
|
|
45
|
+
### `values` is an array of ARRAYS
|
|
46
|
+
|
|
47
|
+
`ValueRange.values` is rows-of-cells, so a single row has to be wrapped:
|
|
48
|
+
`[["a", "b", "c"]]`. A flat array is rejected as the wrong type. That is
|
|
49
|
+
`encoding: "rows"`, and it is a different keyword from `array` by one word.
|
|
50
|
+
|
|
51
|
+
### The scope is the full `spreadsheets` one, deliberately
|
|
52
|
+
|
|
53
|
+
Not `drive.file`. `append` writes to a spreadsheet the user names by id, and
|
|
54
|
+
`drive.file` only reaches files **the app itself created** — so it would work
|
|
55
|
+
throughout testing, where the app made the sheet, and fail against the document
|
|
56
|
+
somebody actually wants to append to. Read from the discovery document's scopes
|
|
57
|
+
for this exact method.
|
|
58
|
+
|
|
59
|
+
### No sandbox, and no idempotency
|
|
60
|
+
|
|
61
|
+
`sandbox` is `none` — **checked**. Google has no test estate for Sheets: a test
|
|
62
|
+
spreadsheet is a real one in a real Drive, so every append is real.
|
|
63
|
+
|
|
64
|
+
`values.append` takes no idempotency key; the discovery document offers neither
|
|
65
|
+
a header nor a parameter for one. So it is `unsafe-to-replay` with no way to
|
|
66
|
+
make it safe, and a retried durable run appends a **second row**.
|
|
67
|
+
|
|
68
|
+
### Access tokens last one hour
|
|
69
|
+
|
|
70
|
+
Google's do. A connection that is never refreshed stops working within the day,
|
|
71
|
+
which is why `refreshToken` is required rather than optional — and Google only
|
|
72
|
+
issues one when the consent request asked for offline access.
|
|
73
|
+
|
|
74
|
+
[0.1.0]: https://github.com/Fancy-Friends/google-sheets/releases/tag/v0.1.0
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Particle Academy
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: fancy-google-sheets
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Google Sheets for Python — the service descriptor, its faker, its webhook verification, and one function per operation. Plain HTTP; no vendor SDK.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Fancy-Friends/google-sheets
|
|
6
|
+
Project-URL: Issues, https://github.com/Fancy-Friends/google-sheets/issues
|
|
7
|
+
Project-URL: Source, https://github.com/Fancy-Friends/google-sheets
|
|
8
|
+
Author: Particle Academy
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: api,connector,fancy-flow,google_sheets,particle-academy,productivity
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# Google Sheets
|
|
24
|
+
|
|
25
|
+
Google Sheets for [fancy-flow][flow] — as **four imported, versioned packages**, one
|
|
26
|
+
per runtime. Not vendored source: a copy cannot be upgraded, and third-party APIs
|
|
27
|
+
change.
|
|
28
|
+
|
|
29
|
+
[flow]: https://github.com/Particle-Academy/fancy-flow
|
|
30
|
+
|
|
31
|
+
| Runtime | Package | Install |
|
|
32
|
+
|---|---|---|
|
|
33
|
+
| Authoring surface (every host) | `@particle-academy/google-sheets-ui` | `npm install @particle-academy/google-sheets-ui` |
|
|
34
|
+
| Node | `@particle-academy/google-sheets-js` | `npm install @particle-academy/google-sheets-js` |
|
|
35
|
+
| PHP 8.4+ | `particle-academy/google-sheets-php` | `composer require particle-academy/google-sheets-php` |
|
|
36
|
+
| Python 3.11+ | `fancy-google-sheets` | `pip install fancy-google-sheets` |
|
|
37
|
+
|
|
38
|
+
The `ui` package is the editor surface and is React on every host — a PHP or
|
|
39
|
+
Python project installs it *and* its own runtime package, and never the `js` one.
|
|
40
|
+
|
|
41
|
+
## What it costs you
|
|
42
|
+
|
|
43
|
+
One dependency: `@particle-academy/fancy-connector-core` (or
|
|
44
|
+
`particle-academy/fancy-connector-core` on Composer), which the `js` and `php`
|
|
45
|
+
packages pull in themselves. The Python package has **zero** runtime
|
|
46
|
+
dependencies.
|
|
47
|
+
|
|
48
|
+
**No Google Sheets SDK.** Plain HTTP, deliberately: a vendor SDK is third-party code
|
|
49
|
+
subject to the kit's full approval bar, and one per provider is hundreds of
|
|
50
|
+
dependencies nobody is tracking.
|
|
51
|
+
|
|
52
|
+
## Run it before you have credentials
|
|
53
|
+
|
|
54
|
+
Every operation ships a **faker**, whether or not Google Sheets has a sandbox. Set a
|
|
55
|
+
node's mode to `fake` and it returns the shape Google Sheets actually publishes — the
|
|
56
|
+
same field names, deterministically — so you can wire the downstream nodes before
|
|
57
|
+
touching an account, a key, or a network.
|
|
58
|
+
|
|
59
|
+
## This repository is generated
|
|
60
|
+
|
|
61
|
+
`provider/` is the source. Everything under `packages/` is emitted from it and
|
|
62
|
+
**must not be hand-edited** — CI regenerates and diffs on every push, and the
|
|
63
|
+
next protocol sync destroys anything it finds. See [`AGENTS.md`](AGENTS.md).
|
|
64
|
+
|
|
65
|
+
## Two namespaces, which do not match on purpose
|
|
66
|
+
|
|
67
|
+
The repo is `github.com/Fancy-Friends/google-sheets`; the packages publish under
|
|
68
|
+
`particle-academy`. Nothing derives one from the other — the names come from
|
|
69
|
+
weaver's `friends.json` and nowhere else.
|
|
70
|
+
|
|
71
|
+
## Licence
|
|
72
|
+
|
|
73
|
+
MIT.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Google Sheets
|
|
2
|
+
|
|
3
|
+
Google Sheets for [fancy-flow][flow] — as **four imported, versioned packages**, one
|
|
4
|
+
per runtime. Not vendored source: a copy cannot be upgraded, and third-party APIs
|
|
5
|
+
change.
|
|
6
|
+
|
|
7
|
+
[flow]: https://github.com/Particle-Academy/fancy-flow
|
|
8
|
+
|
|
9
|
+
| Runtime | Package | Install |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| Authoring surface (every host) | `@particle-academy/google-sheets-ui` | `npm install @particle-academy/google-sheets-ui` |
|
|
12
|
+
| Node | `@particle-academy/google-sheets-js` | `npm install @particle-academy/google-sheets-js` |
|
|
13
|
+
| PHP 8.4+ | `particle-academy/google-sheets-php` | `composer require particle-academy/google-sheets-php` |
|
|
14
|
+
| Python 3.11+ | `fancy-google-sheets` | `pip install fancy-google-sheets` |
|
|
15
|
+
|
|
16
|
+
The `ui` package is the editor surface and is React on every host — a PHP or
|
|
17
|
+
Python project installs it *and* its own runtime package, and never the `js` one.
|
|
18
|
+
|
|
19
|
+
## What it costs you
|
|
20
|
+
|
|
21
|
+
One dependency: `@particle-academy/fancy-connector-core` (or
|
|
22
|
+
`particle-academy/fancy-connector-core` on Composer), which the `js` and `php`
|
|
23
|
+
packages pull in themselves. The Python package has **zero** runtime
|
|
24
|
+
dependencies.
|
|
25
|
+
|
|
26
|
+
**No Google Sheets SDK.** Plain HTTP, deliberately: a vendor SDK is third-party code
|
|
27
|
+
subject to the kit's full approval bar, and one per provider is hundreds of
|
|
28
|
+
dependencies nobody is tracking.
|
|
29
|
+
|
|
30
|
+
## Run it before you have credentials
|
|
31
|
+
|
|
32
|
+
Every operation ships a **faker**, whether or not Google Sheets has a sandbox. Set a
|
|
33
|
+
node's mode to `fake` and it returns the shape Google Sheets actually publishes — the
|
|
34
|
+
same field names, deterministically — so you can wire the downstream nodes before
|
|
35
|
+
touching an account, a key, or a network.
|
|
36
|
+
|
|
37
|
+
## This repository is generated
|
|
38
|
+
|
|
39
|
+
`provider/` is the source. Everything under `packages/` is emitted from it and
|
|
40
|
+
**must not be hand-edited** — CI regenerates and diffs on every push, and the
|
|
41
|
+
next protocol sync destroys anything it finds. See [`AGENTS.md`](AGENTS.md).
|
|
42
|
+
|
|
43
|
+
## Two namespaces, which do not match on purpose
|
|
44
|
+
|
|
45
|
+
The repo is `github.com/Fancy-Friends/google-sheets`; the packages publish under
|
|
46
|
+
`particle-academy`. Nothing derives one from the other — the names come from
|
|
47
|
+
weaver's `friends.json` and nowhere else.
|
|
48
|
+
|
|
49
|
+
## Licence
|
|
50
|
+
|
|
51
|
+
MIT.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "fancy-google-sheets"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Google Sheets for Python — the service descriptor, its faker, its webhook verification, and one function per operation. Plain HTTP; no vendor SDK."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
# 3.11 matches fancy-flow-py's floor: 3.10 reaches end of life on 2026-10-31,
|
|
11
|
+
# and a floor that dies before the package's second release is not a floor.
|
|
12
|
+
requires-python = ">=3.11"
|
|
13
|
+
license = "MIT"
|
|
14
|
+
license-files = ["LICENSE"]
|
|
15
|
+
authors = [{ name = "Particle Academy" }]
|
|
16
|
+
keywords = ["google_sheets", "productivity", "connector", "api", "fancy-flow", "particle-academy"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 3 - Alpha",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Topic :: Software Development :: Libraries",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
# ZERO runtime dependencies, and that is a design constraint rather than an
|
|
29
|
+
# accident. There is no Python twin of fancy-connector-core to depend on, and a
|
|
30
|
+
# vendor SDK is third-party code subject to the kit's full approval bar — one
|
|
31
|
+
# SDK per provider is hundreds of dependencies nobody is tracking. The HTTP is
|
|
32
|
+
# stdlib `urllib`; the HMAC is stdlib `hmac`.
|
|
33
|
+
dependencies = []
|
|
34
|
+
|
|
35
|
+
[project.urls]
|
|
36
|
+
Homepage = "https://github.com/Fancy-Friends/google-sheets"
|
|
37
|
+
Issues = "https://github.com/Fancy-Friends/google-sheets/issues"
|
|
38
|
+
Source = "https://github.com/Fancy-Friends/google-sheets"
|
|
39
|
+
|
|
40
|
+
[dependency-groups]
|
|
41
|
+
# Not optional. A package with no way to run its tests reports green by doing
|
|
42
|
+
# nothing, which is the one defect that hides itself.
|
|
43
|
+
test = ["pytest>=8.0"]
|
|
44
|
+
lint = ["ruff>=0.16"]
|
|
45
|
+
typecheck = ["mypy>=1.11"]
|
|
46
|
+
dev = [{ include-group = "test" }, { include-group = "lint" }, { include-group = "typecheck" }]
|
|
47
|
+
|
|
48
|
+
[tool.hatch.build.targets.wheel]
|
|
49
|
+
packages = ["src/fancy_google_sheets"]
|
|
50
|
+
|
|
51
|
+
[tool.hatch.build.targets.sdist]
|
|
52
|
+
include = ["/src", "/tests", "/README.md", "/CHANGELOG.md", "/LICENSE"]
|
|
53
|
+
|
|
54
|
+
[tool.pytest.ini_options]
|
|
55
|
+
testpaths = ["tests"]
|
|
56
|
+
# importlib mode pairs with src-layout: the working tree is never on sys.path,
|
|
57
|
+
# so the tests exercise the INSTALLED package. Under the default mode a missing
|
|
58
|
+
# py.typed or an unshipped file passes locally and breaks for every user.
|
|
59
|
+
addopts = "--import-mode=importlib -ra"
|
|
60
|
+
|
|
61
|
+
[tool.ruff]
|
|
62
|
+
line-length = 100
|
|
63
|
+
src = ["src", "tests"]
|
|
64
|
+
target-version = "py311"
|
|
65
|
+
|
|
66
|
+
[tool.ruff.lint]
|
|
67
|
+
# `S` — flake8-bandit — is ON, and it is the one addition worth arguing for: this
|
|
68
|
+
# package handles a credential, builds an HMAC, and opens a URL. Security lint
|
|
69
|
+
# belongs on exactly this code.
|
|
70
|
+
#
|
|
71
|
+
# It also makes the two `# noqa: S310` in _runtime.py MEANINGFUL. Without `S`
|
|
72
|
+
# selected, ruff reports them as unused directives (RUF100) and the obvious fix
|
|
73
|
+
# is to delete them — which quietly removes a security annotation because a
|
|
74
|
+
# linter was not looking for it.
|
|
75
|
+
select = ["E", "F", "I", "UP", "B", "SIM", "RUF", "N", "C4", "PT", "S"]
|
|
76
|
+
|
|
77
|
+
[tool.ruff.lint.per-file-ignores]
|
|
78
|
+
# pytest's whole idiom is bare `assert`. S101 would fail every test file.
|
|
79
|
+
"tests/*" = ["S101"]
|
|
80
|
+
|
|
81
|
+
[tool.mypy]
|
|
82
|
+
python_version = "3.11"
|
|
83
|
+
packages = ["fancy_google_sheets"]
|
|
84
|
+
mypy_path = "src"
|
|
85
|
+
strict = true
|
|
86
|
+
disallow_any_expr = false
|
|
87
|
+
disallow_any_explicit = false
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# GENERATED FILE — do not edit.
|
|
2
|
+
#
|
|
3
|
+
# Emitted from provider/manifest.json by weaver's generator.
|
|
4
|
+
# A hand-edit here is destroyed by the next protocol sync, which is worse than
|
|
5
|
+
# being rejected, because it works until it silently does not. Fix
|
|
6
|
+
# provider/manifest.json (or weaver's template/) and regenerate:
|
|
7
|
+
#
|
|
8
|
+
# npm run provider -- google_sheets
|
|
9
|
+
|
|
10
|
+
"""Google Sheets for Python.
|
|
11
|
+
|
|
12
|
+
The service descriptor, its faker, its delivery contract, and one function
|
|
13
|
+
per operation — plain HTTP on the stdlib, no vendor SDK and no runtime
|
|
14
|
+
dependency.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from ._fake import FakeValues
|
|
20
|
+
from .actions.row_append import row_append
|
|
21
|
+
from .faker import respond
|
|
22
|
+
from .service import BASE_URLS, CONNECTOR_API_VERSION, REQUIRES, SANDBOX, SERVICE, TITLE, descriptor
|
|
23
|
+
|
|
24
|
+
__version__ = "0.1.0"
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"BASE_URLS",
|
|
28
|
+
"CONNECTOR_API_VERSION",
|
|
29
|
+
"REQUIRES",
|
|
30
|
+
"SANDBOX",
|
|
31
|
+
"SERVICE",
|
|
32
|
+
"TITLE",
|
|
33
|
+
"FakeValues",
|
|
34
|
+
"descriptor",
|
|
35
|
+
"respond",
|
|
36
|
+
"row_append",
|
|
37
|
+
]
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
# GENERATED FILE — do not edit.
|
|
2
|
+
#
|
|
3
|
+
# Emitted from provider/manifest.json (via weaver's
|
|
4
|
+
# template/embed/py/_fake.py) by weaver's generator.
|
|
5
|
+
# A hand-edit here is destroyed by the next protocol sync, which is worse than
|
|
6
|
+
# being rejected, because it works until it silently does not. Fix
|
|
7
|
+
# provider/manifest.json (via weaver's template/embed/py/_fake.py) (or
|
|
8
|
+
# weaver's template/) and regenerate:
|
|
9
|
+
#
|
|
10
|
+
# npm run provider -- google_sheets
|
|
11
|
+
|
|
12
|
+
"""Deterministic faker values — bit-for-bit with TypeScript and PHP.
|
|
13
|
+
|
|
14
|
+
PROVENANCE — read before editing.
|
|
15
|
+
|
|
16
|
+
This is the SINGLE SOURCE for the Python faker helpers. It exists because
|
|
17
|
+
``fancy-connector-core`` has a TypeScript implementation and a PHP twin and
|
|
18
|
+
**no Python twin at all**, so a generated ``fancy-<provider>`` package has no
|
|
19
|
+
shared runtime to import. Every generated package carries a copy emitted from
|
|
20
|
+
this file, and ``new-provider.mjs --check`` fails CI when a copy differs.
|
|
21
|
+
|
|
22
|
+
The permanent fix is a Python ``fancy-connector-core``. When it exists, this
|
|
23
|
+
file becomes a re-export and every provider picks it up on the next protocol
|
|
24
|
+
sync.
|
|
25
|
+
|
|
26
|
+
## Bit-for-bit identical is the whole point
|
|
27
|
+
|
|
28
|
+
Not "similar": the same FNV-1a seed and the same xorshift32 sequence, so a
|
|
29
|
+
golden fixture asserts the exact faked payload and ALL THREE runtimes have to
|
|
30
|
+
produce it. That turns the faker into a parity test rather than a convenience —
|
|
31
|
+
which matters, because cross-runtime drift does not fail loudly. It completes,
|
|
32
|
+
down one path, with no error.
|
|
33
|
+
|
|
34
|
+
Python integers are unbounded, so every 32-bit operation is masked back into
|
|
35
|
+
range. Dropping one of those masks does not break anything visibly; it just
|
|
36
|
+
makes the runtimes diverge after a few hundred calls, which is the worst
|
|
37
|
+
possible way for this to fail.
|
|
38
|
+
|
|
39
|
+
## Deterministic, and obviously fake
|
|
40
|
+
|
|
41
|
+
Same inputs, same output — always. A faker returning a fresh uuid every call
|
|
42
|
+
cannot be asserted on, so its fixtures degrade to "it did not throw", which is
|
|
43
|
+
the assertion that catches nothing. And the values are obviously synthetic ON
|
|
44
|
+
PURPOSE — ``fake_``-prefixed ids, ``example.test`` hosts, round numbers. Nobody
|
|
45
|
+
should ever look at a faked result and wonder whether it moved real money.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
from __future__ import annotations
|
|
49
|
+
|
|
50
|
+
import json
|
|
51
|
+
from datetime import UTC, datetime, timedelta
|
|
52
|
+
from typing import Any
|
|
53
|
+
|
|
54
|
+
MASK = 0xFFFFFFFF
|
|
55
|
+
|
|
56
|
+
# `FakeValues.int` is part of the cross-runtime faker API — `fake.int(min, max)`
|
|
57
|
+
# in TypeScript, PHP and here — so the method keeps that name. Inside the class
|
|
58
|
+
# body it then shadows the builtin, and every LATER annotation reading `int`
|
|
59
|
+
# resolves to the method instead of the type. This alias is what the annotations
|
|
60
|
+
# after it use.
|
|
61
|
+
_Int = int
|
|
62
|
+
|
|
63
|
+
#: The instant every faker counts from. A constant rather than the clock,
|
|
64
|
+
#: because a fixture asserting on ``created`` must not start failing tomorrow.
|
|
65
|
+
FAKE_EPOCH = "2026-01-01T00:00:00.000Z"
|
|
66
|
+
|
|
67
|
+
_FNV_OFFSET = 0x811C9DC5
|
|
68
|
+
_FNV_PRIME = 0x01000193
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _stable_json(value: Any) -> str:
|
|
72
|
+
"""Render a value the way ``JSON.stringify`` would, with sorted object keys.
|
|
73
|
+
|
|
74
|
+
Key order must not change a seed. ``json.dumps`` preserves insertion order,
|
|
75
|
+
so ``{a, b}`` and ``{b, a}`` would hash differently and "same inputs, same
|
|
76
|
+
output" would hold only for dicts that happened to be built in the same
|
|
77
|
+
order — the kind of almost-true that survives review and fails in a fixture
|
|
78
|
+
months later.
|
|
79
|
+
"""
|
|
80
|
+
if isinstance(value, dict):
|
|
81
|
+
parts = [
|
|
82
|
+
f"{json.dumps(str(key))}:{_stable_json(item)}"
|
|
83
|
+
for key, item in sorted(value.items(), key=lambda pair: str(pair[0]))
|
|
84
|
+
if item is not ...
|
|
85
|
+
]
|
|
86
|
+
return "{" + ",".join(parts) + "}"
|
|
87
|
+
|
|
88
|
+
if isinstance(value, (list, tuple)):
|
|
89
|
+
return "[" + ",".join(_stable_json(item) for item in value) + "]"
|
|
90
|
+
|
|
91
|
+
# `separators` matters: JavaScript emits no spaces, and a space here would
|
|
92
|
+
# change every seed.
|
|
93
|
+
return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def seed_from(*parts: Any) -> int:
|
|
97
|
+
"""FNV-1a over the stable rendering of the parts. Twin of ``seedFrom``."""
|
|
98
|
+
text = "|".join(part if isinstance(part, str) else _stable_json(part) for part in parts)
|
|
99
|
+
|
|
100
|
+
hash_ = _FNV_OFFSET
|
|
101
|
+
# JavaScript hashes UTF-16 code units, so a character outside the BMP
|
|
102
|
+
# contributes two of them. Encoding to UTF-16-LE and reading pairs is what
|
|
103
|
+
# keeps a provider name with an emoji in it seeding identically.
|
|
104
|
+
for unit in _utf16_units(text):
|
|
105
|
+
hash_ ^= unit
|
|
106
|
+
hash_ = (hash_ * _FNV_PRIME) & MASK
|
|
107
|
+
|
|
108
|
+
return hash_
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _utf16_units(text: str) -> list[int]:
|
|
112
|
+
raw = text.encode("utf-16-le")
|
|
113
|
+
|
|
114
|
+
return [raw[i] | (raw[i + 1] << 8) for i in range(0, len(raw), 2)]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def seed_for_call(service: str, operation: str, config: dict[str, Any] | None) -> int:
|
|
118
|
+
"""The seed for one faked call: service, operation, and the caller's config."""
|
|
119
|
+
return seed_from(service, operation, config or {})
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class FakeValues:
|
|
123
|
+
"""Deterministic value helpers handed to a faker.
|
|
124
|
+
|
|
125
|
+
Small on purpose. A faker's job is to return the SHAPE the provider returns
|
|
126
|
+
— the field names a downstream node will reference — not to simulate the
|
|
127
|
+
provider's business logic.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
def __init__(self, seed: int) -> None:
|
|
131
|
+
masked = seed & MASK
|
|
132
|
+
self._state = masked if masked != 0 else 0x9E3779B9
|
|
133
|
+
|
|
134
|
+
def _next(self) -> int:
|
|
135
|
+
"""xorshift32, matching the JS generator step for step."""
|
|
136
|
+
state = self._state
|
|
137
|
+
state ^= (state << 13) & MASK
|
|
138
|
+
state &= MASK
|
|
139
|
+
state ^= state >> 17
|
|
140
|
+
state ^= (state << 5) & MASK
|
|
141
|
+
state &= MASK
|
|
142
|
+
self._state = state
|
|
143
|
+
|
|
144
|
+
return state
|
|
145
|
+
|
|
146
|
+
def hex(self, length: _Int) -> str:
|
|
147
|
+
"""A stable lowercase hex string of ``length`` characters."""
|
|
148
|
+
out = ""
|
|
149
|
+
while len(out) < length:
|
|
150
|
+
out += format(self._next(), "08x")
|
|
151
|
+
|
|
152
|
+
return out[:length]
|
|
153
|
+
|
|
154
|
+
def id(self, prefix: str) -> str:
|
|
155
|
+
"""A stable id with the provider's usual prefix: ``id("ch")`` -> ``ch_fake_1a2b3c``."""
|
|
156
|
+
return f"{prefix}_fake_{self.hex(12)}"
|
|
157
|
+
|
|
158
|
+
def int(self, minimum: int, maximum: int) -> int:
|
|
159
|
+
"""A stable integer in ``[minimum, maximum]``."""
|
|
160
|
+
return minimum + (self._next() % max(1, maximum - minimum + 1))
|
|
161
|
+
|
|
162
|
+
def pick(self, options: list[Any]) -> Any:
|
|
163
|
+
"""Pick a stable element of a list."""
|
|
164
|
+
return options[self._next() % len(options)]
|
|
165
|
+
|
|
166
|
+
def timestamp(self, offset_seconds: _Int = 0) -> str:
|
|
167
|
+
"""A fixed ISO-8601 instant, offset by whole seconds. Never ``now()``."""
|
|
168
|
+
base = datetime(2026, 1, 1, tzinfo=UTC) + timedelta(seconds=offset_seconds)
|
|
169
|
+
|
|
170
|
+
return base.strftime("%Y-%m-%dT%H:%M:%S") + ".000Z"
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
# GENERATED FILE — do not edit.
|
|
2
|
+
#
|
|
3
|
+
# Emitted from provider/manifest.json (via weaver's
|
|
4
|
+
# template/embed/py/_runtime.py) by weaver's generator.
|
|
5
|
+
# A hand-edit here is destroyed by the next protocol sync, which is worse than
|
|
6
|
+
# being rejected, because it works until it silently does not. Fix
|
|
7
|
+
# provider/manifest.json (via weaver's template/embed/py/_runtime.py) (or
|
|
8
|
+
# weaver's template/) and regenerate:
|
|
9
|
+
#
|
|
10
|
+
# npm run provider -- google_sheets
|
|
11
|
+
|
|
12
|
+
"""The minimum connector runtime, in the standard library only.
|
|
13
|
+
|
|
14
|
+
PROVENANCE — read before editing.
|
|
15
|
+
|
|
16
|
+
This is the SINGLE SOURCE for the Python connector runtime, and it is
|
|
17
|
+
deliberately much smaller than ``@particle-academy/fancy-connector-core``. It
|
|
18
|
+
exists because that package has a TypeScript implementation and a PHP twin and
|
|
19
|
+
**no Python twin at all**. Every generated ``fancy-<provider>`` package carries
|
|
20
|
+
a copy emitted from this file, and ``new-provider.mjs --check`` fails CI when a
|
|
21
|
+
copy differs.
|
|
22
|
+
|
|
23
|
+
The permanent fix is a Python ``fancy-connector-core``. When it exists, this
|
|
24
|
+
file becomes a re-export and every provider picks it up on the next protocol
|
|
25
|
+
sync.
|
|
26
|
+
|
|
27
|
+
## What it does, and what it deliberately does not
|
|
28
|
+
|
|
29
|
+
It owns the WIRE: the estate, the auth placement, one call path, the faker
|
|
30
|
+
branch, an idempotency header, and HMAC delivery verification.
|
|
31
|
+
|
|
32
|
+
It owns NO GATE. Approval, liveness, consent, second review and every journal
|
|
33
|
+
belong to the host, because each is enforced in ONE place and every connector
|
|
34
|
+
inherits it from the dispatch path rather than implementing it.
|
|
35
|
+
|
|
36
|
+
Three properties that are asserted rather than promised:
|
|
37
|
+
|
|
38
|
+
- **Nothing here reads the environment.** Credentials are arguments. A package
|
|
39
|
+
that reached for ``os.environ`` would bypass the host's discipline entirely.
|
|
40
|
+
- **Nothing here retries an ambiguous failure.** A request that may or may not
|
|
41
|
+
have arrived is repeated only when the caller has said repeating it is
|
|
42
|
+
harmless.
|
|
43
|
+
- **Nothing here phones home.** No telemetry, no central service, and no URL
|
|
44
|
+
this module contacts that the connector did not name.
|
|
45
|
+
|
|
46
|
+
## Zero dependencies is a constraint, not an accident
|
|
47
|
+
|
|
48
|
+
``urllib`` for HTTP, ``hmac``/``hashlib`` for signatures. A vendor SDK is
|
|
49
|
+
third-party code subject to the kit's full approval bar, and one SDK per
|
|
50
|
+
provider is hundreds of dependencies nobody is tracking.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
from __future__ import annotations
|
|
54
|
+
|
|
55
|
+
import hashlib
|
|
56
|
+
import hmac
|
|
57
|
+
import json
|
|
58
|
+
import time
|
|
59
|
+
import urllib.error
|
|
60
|
+
import urllib.parse
|
|
61
|
+
import urllib.request
|
|
62
|
+
from collections.abc import Callable
|
|
63
|
+
from dataclasses import dataclass, field
|
|
64
|
+
from typing import Any, Literal
|
|
65
|
+
|
|
66
|
+
Mode = Literal["fake", "sandbox", "live", "auto"]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ConnectorError(Exception):
|
|
70
|
+
"""Something went wrong talking to the provider."""
|
|
71
|
+
|
|
72
|
+
def __init__(self, message: str, *, status: int | None = None, retryable: bool = False) -> None:
|
|
73
|
+
super().__init__(message)
|
|
74
|
+
self.status = status
|
|
75
|
+
#: Whether repeating this exact request is known to be harmless. Defaults
|
|
76
|
+
#: to False: an ambiguous failure is only retryable when the caller said
|
|
77
|
+
#: so, not when a retry would be convenient.
|
|
78
|
+
self.retryable = retryable
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class ConnectorConfigError(ConnectorError):
|
|
82
|
+
"""The call was refused before anything was sent. Nothing was attempted."""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ConnectorAuthError(ConnectorError):
|
|
86
|
+
"""The provider rejected the credential."""
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class ConnectorModeError(ConnectorError):
|
|
90
|
+
"""The requested estate does not exist for this provider."""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class PreparedRequest:
|
|
95
|
+
"""An outgoing request, after the service descriptor has authorised it."""
|
|
96
|
+
|
|
97
|
+
method: str
|
|
98
|
+
url: str
|
|
99
|
+
headers: dict[str, str] = field(default_factory=dict)
|
|
100
|
+
query: dict[str, str] = field(default_factory=dict)
|
|
101
|
+
body: bytes | None = None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass
|
|
105
|
+
class ServiceDescriptor:
|
|
106
|
+
"""A provider, as one value shared by every one of its operations."""
|
|
107
|
+
|
|
108
|
+
service: str
|
|
109
|
+
title: str
|
|
110
|
+
sandbox: str
|
|
111
|
+
base_urls: dict[str, str]
|
|
112
|
+
requires: list[str]
|
|
113
|
+
authorize: Callable[[dict[str, str | None], PreparedRequest, str], None]
|
|
114
|
+
faker: Callable[[str, dict[str, Any]], Any]
|
|
115
|
+
idempotency_header: str | None = None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass
|
|
119
|
+
class CallResult:
|
|
120
|
+
"""What one call produced, and which estate produced it."""
|
|
121
|
+
|
|
122
|
+
mode: str
|
|
123
|
+
connection: str | None
|
|
124
|
+
data: Any
|
|
125
|
+
status: int | None = None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass
|
|
129
|
+
class Verification:
|
|
130
|
+
"""Whether an inbound delivery can be trusted, and why not when it cannot."""
|
|
131
|
+
|
|
132
|
+
ok: bool
|
|
133
|
+
reason: str | None = None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
#: The estate kinds a ``sandbox`` mode can actually point at. Mirrors the
|
|
137
|
+
#: TypeScript ``sandboxIsSelectable``.
|
|
138
|
+
SELECTABLE_SANDBOX = ("credential", "base-url", "separate-account")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def resolve_mode(descriptor: ServiceDescriptor, requested: Mode) -> str:
|
|
142
|
+
"""Turn ``auto`` into a real estate, and refuse one the provider does not have.
|
|
143
|
+
|
|
144
|
+
A provider with no sandbox resolving ``sandbox`` to ``live`` would be the
|
|
145
|
+
worst possible reading: it moves real money while the caller believes it did
|
|
146
|
+
not.
|
|
147
|
+
"""
|
|
148
|
+
if requested == "auto":
|
|
149
|
+
return "fake"
|
|
150
|
+
|
|
151
|
+
if requested == "sandbox" and descriptor.sandbox not in SELECTABLE_SANDBOX:
|
|
152
|
+
raise ConnectorModeError(
|
|
153
|
+
f'{descriptor.service}: sandbox was requested but this provider\'s estate is '
|
|
154
|
+
f'"{descriptor.sandbox}", which cannot be selected. Use "fake" to design against '
|
|
155
|
+
f'a shaped response, or "live" deliberately.'
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
return requested
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def call(
|
|
162
|
+
descriptor: ServiceDescriptor,
|
|
163
|
+
*,
|
|
164
|
+
operation: str,
|
|
165
|
+
method: str,
|
|
166
|
+
path: str,
|
|
167
|
+
form: dict[str, Any] | None = None,
|
|
168
|
+
json_body: Any | None = None,
|
|
169
|
+
query: dict[str, Any] | None = None,
|
|
170
|
+
config: dict[str, Any] | None = None,
|
|
171
|
+
credentials: dict[str, str | None] | None = None,
|
|
172
|
+
mode: Mode = "auto",
|
|
173
|
+
connection_id: str | None = None,
|
|
174
|
+
idempotency_key: str | None = None,
|
|
175
|
+
idempotent: bool = False,
|
|
176
|
+
attempts: int = 3,
|
|
177
|
+
timeout: float = 30.0,
|
|
178
|
+
transport: Callable[[PreparedRequest], tuple[int, str]] | None = None,
|
|
179
|
+
) -> CallResult:
|
|
180
|
+
"""Make one call, or fake one.
|
|
181
|
+
|
|
182
|
+
``fake`` mode never touches the network, so a connector is runnable before an
|
|
183
|
+
account, a key or a provider that is up.
|
|
184
|
+
"""
|
|
185
|
+
resolved = resolve_mode(descriptor, mode)
|
|
186
|
+
config = config or {}
|
|
187
|
+
|
|
188
|
+
if resolved == "fake":
|
|
189
|
+
from ._fake import FakeValues, seed_for_call
|
|
190
|
+
|
|
191
|
+
fake = FakeValues(seed_for_call(descriptor.service, operation, config))
|
|
192
|
+
|
|
193
|
+
return CallResult(
|
|
194
|
+
mode="fake",
|
|
195
|
+
connection=connection_id,
|
|
196
|
+
data=descriptor.faker(operation, {"config": config, "fake": fake}),
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
base = descriptor.base_urls.get(resolved)
|
|
200
|
+
if not base:
|
|
201
|
+
raise ConnectorModeError(f"{descriptor.service}: no base URL for mode \"{resolved}\".")
|
|
202
|
+
|
|
203
|
+
credentials = credentials or {}
|
|
204
|
+
missing = [key for key in descriptor.requires if not credentials.get(key)]
|
|
205
|
+
if missing:
|
|
206
|
+
raise ConnectorConfigError(
|
|
207
|
+
f"{descriptor.service}: the connection is missing {', '.join(missing)}."
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
request = PreparedRequest(method=method, url=base.rstrip("/") + path)
|
|
211
|
+
request.query = {k: str(v) for k, v in (query or {}).items() if v is not None}
|
|
212
|
+
|
|
213
|
+
if form is not None:
|
|
214
|
+
request.body = urllib.parse.urlencode(
|
|
215
|
+
{k: v for k, v in form.items() if v is not None}, doseq=False
|
|
216
|
+
).encode()
|
|
217
|
+
request.headers["Content-Type"] = "application/x-www-form-urlencoded"
|
|
218
|
+
elif json_body is not None:
|
|
219
|
+
request.body = json.dumps(json_body, separators=(",", ":")).encode()
|
|
220
|
+
request.headers["Content-Type"] = "application/json"
|
|
221
|
+
|
|
222
|
+
if idempotency_key and descriptor.idempotency_header:
|
|
223
|
+
request.headers[descriptor.idempotency_header] = idempotency_key
|
|
224
|
+
|
|
225
|
+
descriptor.authorize(credentials, request, resolved)
|
|
226
|
+
|
|
227
|
+
send = transport or _urllib_transport
|
|
228
|
+
last: ConnectorError | None = None
|
|
229
|
+
|
|
230
|
+
for attempt in range(1, max(1, attempts) + 1):
|
|
231
|
+
try:
|
|
232
|
+
status, text = send(_with_query(request, timeout))
|
|
233
|
+
except OSError as error: # DNS, connection reset, timeout
|
|
234
|
+
# Nobody can tell whether this arrived. Repeating is safe only when
|
|
235
|
+
# the caller has said so or the request carries an idempotency key.
|
|
236
|
+
last = ConnectorError(
|
|
237
|
+
f"{descriptor.service}: {operation} did not complete ({error}).",
|
|
238
|
+
retryable=idempotent or bool(idempotency_key),
|
|
239
|
+
)
|
|
240
|
+
else:
|
|
241
|
+
if 200 <= status < 300:
|
|
242
|
+
return CallResult(
|
|
243
|
+
mode=resolved,
|
|
244
|
+
connection=connection_id,
|
|
245
|
+
data=json.loads(text) if text else None,
|
|
246
|
+
status=status,
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
last = _classify(descriptor.service, operation, status, text)
|
|
250
|
+
|
|
251
|
+
if not last.retryable or attempt == attempts:
|
|
252
|
+
raise last
|
|
253
|
+
|
|
254
|
+
time.sleep(min(2 ** (attempt - 1), 8))
|
|
255
|
+
|
|
256
|
+
raise last if last else ConnectorError(f"{descriptor.service}: {operation} failed.")
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _with_query(request: PreparedRequest, timeout: float) -> PreparedRequest:
|
|
260
|
+
if not request.query:
|
|
261
|
+
return request
|
|
262
|
+
|
|
263
|
+
separator = "&" if "?" in request.url else "?"
|
|
264
|
+
joined = PreparedRequest(
|
|
265
|
+
method=request.method,
|
|
266
|
+
url=f"{request.url}{separator}{urllib.parse.urlencode(request.query)}",
|
|
267
|
+
headers=dict(request.headers),
|
|
268
|
+
body=request.body,
|
|
269
|
+
)
|
|
270
|
+
joined.headers.setdefault("_timeout", str(timeout))
|
|
271
|
+
|
|
272
|
+
return joined
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _urllib_transport(request: PreparedRequest) -> tuple[int, str]:
|
|
276
|
+
timeout = float(request.headers.pop("_timeout", "30"))
|
|
277
|
+
raw = urllib.request.Request( # noqa: S310 — the URL comes from the descriptor
|
|
278
|
+
request.url,
|
|
279
|
+
data=request.body,
|
|
280
|
+
headers=request.headers,
|
|
281
|
+
method=request.method,
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
try:
|
|
285
|
+
with urllib.request.urlopen(raw, timeout=timeout) as response: # noqa: S310
|
|
286
|
+
return response.status, response.read().decode("utf-8", "replace")
|
|
287
|
+
except urllib.error.HTTPError as error:
|
|
288
|
+
return error.code, error.read().decode("utf-8", "replace")
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _classify(service: str, operation: str, status: int, body: str) -> ConnectorError:
|
|
292
|
+
"""Separate "it was refused" from "nobody can tell"."""
|
|
293
|
+
message = f"{service}: {operation} failed with {status}. {body[:400]}"
|
|
294
|
+
|
|
295
|
+
if status in (401, 403):
|
|
296
|
+
return ConnectorAuthError(message, status=status)
|
|
297
|
+
if status == 429 or status >= 500:
|
|
298
|
+
# A 5xx or a rate limit is the provider saying "try again", which is a
|
|
299
|
+
# different fact from a 4xx saying "this request is wrong".
|
|
300
|
+
return ConnectorError(message, status=status, retryable=True)
|
|
301
|
+
|
|
302
|
+
return ConnectorError(message, status=status)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
_ALGORITHMS = {"sha256": hashlib.sha256, "sha1": hashlib.sha1, "sha512": hashlib.sha512}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def verify_hmac(
|
|
309
|
+
*,
|
|
310
|
+
raw: str,
|
|
311
|
+
signature: str | None,
|
|
312
|
+
secret: str | None,
|
|
313
|
+
payload: Callable[[str, str | None], str],
|
|
314
|
+
algorithm: str,
|
|
315
|
+
encoding: str = "hex",
|
|
316
|
+
tolerance: int | None = None,
|
|
317
|
+
timestamp: str | None = None,
|
|
318
|
+
now: int | None = None,
|
|
319
|
+
) -> Verification:
|
|
320
|
+
"""Verify one inbound delivery.
|
|
321
|
+
|
|
322
|
+
Refuses rather than accepts on every missing input. That asymmetry is the
|
|
323
|
+
whole safety property: an unverifiable endpoint is a stranger's button for
|
|
324
|
+
starting workflows in your account, and defaulting to "allow" would make
|
|
325
|
+
every misconfiguration into an open door that looks shut.
|
|
326
|
+
|
|
327
|
+
``raw`` must be the body EXACTLY as received. Re-serialised JSON changes key
|
|
328
|
+
order and whitespace and produces a mismatch that looks precisely like a
|
|
329
|
+
wrong secret.
|
|
330
|
+
"""
|
|
331
|
+
if not secret:
|
|
332
|
+
return Verification(False, "no signing secret is configured for this connection")
|
|
333
|
+
if not signature:
|
|
334
|
+
return Verification(False, "the delivery carried no signature")
|
|
335
|
+
|
|
336
|
+
digest = _ALGORITHMS.get(algorithm)
|
|
337
|
+
if digest is None:
|
|
338
|
+
return Verification(False, f'unsupported signature algorithm "{algorithm}"')
|
|
339
|
+
|
|
340
|
+
if tolerance is not None:
|
|
341
|
+
if not timestamp:
|
|
342
|
+
return Verification(
|
|
343
|
+
False, "the delivery carried no timestamp, and this scheme signs one"
|
|
344
|
+
)
|
|
345
|
+
try:
|
|
346
|
+
sent = int(float(timestamp))
|
|
347
|
+
except (TypeError, ValueError):
|
|
348
|
+
return Verification(False, f'the delivery timestamp "{timestamp}" is not a number')
|
|
349
|
+
|
|
350
|
+
current = int(time.time()) if now is None else now
|
|
351
|
+
if abs(current - sent) > tolerance:
|
|
352
|
+
return Verification(
|
|
353
|
+
False,
|
|
354
|
+
f"the delivery is outside the {tolerance}s replay window "
|
|
355
|
+
f"({abs(current - sent)}s old)",
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
computed = hmac.new(secret.encode(), payload(raw, timestamp).encode(), digest)
|
|
359
|
+
expected = computed.hexdigest() if encoding == "hex" else _b64(computed.digest())
|
|
360
|
+
|
|
361
|
+
# Constant time, so a signature cannot be discovered one character at a time.
|
|
362
|
+
if not hmac.compare_digest(expected, signature):
|
|
363
|
+
return Verification(False, "the signature does not match")
|
|
364
|
+
|
|
365
|
+
return Verification(True)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _b64(raw: bytes) -> str:
|
|
369
|
+
import base64
|
|
370
|
+
|
|
371
|
+
return base64.b64encode(raw).decode()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# GENERATED FILE — do not edit.
|
|
2
|
+
#
|
|
3
|
+
# Emitted from provider/actions/ by weaver's generator.
|
|
4
|
+
# A hand-edit here is destroyed by the next protocol sync, which is worse than
|
|
5
|
+
# being rejected, because it works until it silently does not. Fix
|
|
6
|
+
# provider/actions/ (or weaver's template/) and regenerate:
|
|
7
|
+
#
|
|
8
|
+
# npm run provider -- google_sheets
|
|
9
|
+
|
|
10
|
+
from .row_append import row_append
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"row_append",
|
|
14
|
+
]
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# GENERATED FILE — do not edit.
|
|
2
|
+
#
|
|
3
|
+
# Emitted from provider/actions/row-append.json by weaver's generator.
|
|
4
|
+
# A hand-edit here is destroyed by the next protocol sync, which is worse than
|
|
5
|
+
# being rejected, because it works until it silently does not. Fix
|
|
6
|
+
# provider/actions/row-append.json (or weaver's template/) and regenerate:
|
|
7
|
+
#
|
|
8
|
+
# npm run provider -- google_sheets
|
|
9
|
+
|
|
10
|
+
"""Append a row to a Google Sheet.
|
|
11
|
+
|
|
12
|
+
POST /v4/spreadsheets/{spreadsheetId}/values/{range}:append —
|
|
13
|
+
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append
|
|
14
|
+
|
|
15
|
+
This describes the request. `call` resolves the connection, picks the
|
|
16
|
+
estate, and either calls Google Sheets or calls the faker.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Any
|
|
22
|
+
from urllib.parse import quote
|
|
23
|
+
|
|
24
|
+
from .._runtime import CallResult, ConnectorConfigError, Mode, call
|
|
25
|
+
from ..service import descriptor
|
|
26
|
+
|
|
27
|
+
OPERATION = "row_append"
|
|
28
|
+
METHOD = "POST"
|
|
29
|
+
PATH = "/v4/spreadsheets/{spreadsheetId}/values/{range}:append"
|
|
30
|
+
SIDE_EFFECTS = "unsafe-to-replay"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def body(config: dict[str, Any]) -> dict[str, Any]:
|
|
34
|
+
"""Build the JSON body for one call, failing loudly and specifically."""
|
|
35
|
+
if config.get("spreadsheetId") is None or config.get("spreadsheetId") == "":
|
|
36
|
+
raise ConnectorConfigError(
|
|
37
|
+
"row_append: \"spreadsheetId\" is required (Spreadsheet ID)."
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
if config.get("range") is None or config.get("range") == "":
|
|
41
|
+
raise ConnectorConfigError(
|
|
42
|
+
"row_append: \"range\" is required (Range)."
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
if config.get("values") is None or config.get("values") == "":
|
|
46
|
+
raise ConnectorConfigError(
|
|
47
|
+
"row_append: \"values\" is required (Row values)."
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
out: dict[str, Any] = {}
|
|
51
|
+
_value = config.get("values")
|
|
52
|
+
out["values"] = [_values_list(config.get("values"))]
|
|
53
|
+
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def path(config: dict[str, Any]) -> str:
|
|
59
|
+
"""The request path, with each config value URL-ENCODED into it.
|
|
60
|
+
|
|
61
|
+
`PATH` above is the TEMPLATE, which is what the descriptor advertises;
|
|
62
|
+
this is what a caller sends. A value interpolated raw changes WHICH URL is
|
|
63
|
+
called — a range like `Sheet1!A:B`, or a sheet named `Q1/Q2` — and the
|
|
64
|
+
provider answers 404 about the document rather than about the encoding.
|
|
65
|
+
"""
|
|
66
|
+
return (
|
|
67
|
+
"/v4/spreadsheets/"
|
|
68
|
+
+ quote(str(config.get("spreadsheetId") or ""), safe="")
|
|
69
|
+
+ "/values/"
|
|
70
|
+
+ quote(str(config.get("range") or ""), safe="")
|
|
71
|
+
+ ":append"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def query(config: dict[str, Any]) -> dict[str, Any]:
|
|
76
|
+
"""The QUERY parameters, which are not the same as the body.
|
|
77
|
+
|
|
78
|
+
A POST can carry both. Sent in the body instead, a parameter like Sheets'
|
|
79
|
+
`valueInputOption` is IGNORED and the provider falls back to its own
|
|
80
|
+
default — so the request succeeds and quietly does the wrong thing.
|
|
81
|
+
"""
|
|
82
|
+
out: dict[str, Any] = {}
|
|
83
|
+
_value = config.get("valueInputOption")
|
|
84
|
+
if _value is not None and _value != "":
|
|
85
|
+
out["valueInputOption"] = str(_value)
|
|
86
|
+
_value = config.get("insertDataOption")
|
|
87
|
+
if _value is not None and _value != "":
|
|
88
|
+
out["insertDataOption"] = str(_value)
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
def row_append(
|
|
92
|
+
config: dict[str, Any],
|
|
93
|
+
*,
|
|
94
|
+
credentials: dict[str, str | None] | None = None,
|
|
95
|
+
mode: Mode = "auto",
|
|
96
|
+
connection_id: str | None = None,
|
|
97
|
+
attempts: int = 3,
|
|
98
|
+
) -> CallResult:
|
|
99
|
+
"""Append a row to a Google Sheet."""
|
|
100
|
+
return call(
|
|
101
|
+
descriptor(),
|
|
102
|
+
operation=OPERATION,
|
|
103
|
+
method=METHOD,
|
|
104
|
+
path=PATH,
|
|
105
|
+
json_body=body(config),
|
|
106
|
+
config=config,
|
|
107
|
+
credentials=credentials,
|
|
108
|
+
mode=mode,
|
|
109
|
+
connection_id=connection_id,
|
|
110
|
+
attempts=attempts,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _values_list(value: Any) -> list[str]:
|
|
115
|
+
"""One value, a ","-separated string, or a list — all end up a list."""
|
|
116
|
+
if isinstance(value, list):
|
|
117
|
+
items = [str(item) for item in value]
|
|
118
|
+
elif isinstance(value, str):
|
|
119
|
+
items = value.split(",")
|
|
120
|
+
else:
|
|
121
|
+
return []
|
|
122
|
+
|
|
123
|
+
return [item.strip() for item in items if item.strip()]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# GENERATED FILE — do not edit.
|
|
2
|
+
#
|
|
3
|
+
# Emitted from provider/fixtures/ by weaver's generator.
|
|
4
|
+
# A hand-edit here is destroyed by the next protocol sync, which is worse than
|
|
5
|
+
# being rejected, because it works until it silently does not. Fix
|
|
6
|
+
# provider/fixtures/ (or weaver's template/) and regenerate:
|
|
7
|
+
#
|
|
8
|
+
# npm run provider -- google_sheets
|
|
9
|
+
|
|
10
|
+
"""The Google Sheets faker.
|
|
11
|
+
|
|
12
|
+
Bit-for-bit identical to the TypeScript and PHP fakers: the same FNV-1a seed
|
|
13
|
+
and the same xorshift32 sequence, so a golden fixture asserts the exact
|
|
14
|
+
faked payload and ALL THREE runtimes have to produce it. That turns the
|
|
15
|
+
faker into a parity test rather than a convenience — which matters, because
|
|
16
|
+
cross-runtime drift does not fail loudly. It completes, down one path, with
|
|
17
|
+
no error.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from ._fake import FakeValues
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _row_append(config: dict[str, Any], fake: FakeValues) -> Any:
|
|
28
|
+
bound_spreadsheetid = (
|
|
29
|
+
str(_v)
|
|
30
|
+
if (_v := config.get("spreadsheetId")) is not None and _v != ""
|
|
31
|
+
else fake.id("1Sheet")
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
"spreadsheetId": bound_spreadsheetid,
|
|
36
|
+
"tableRange": "Sheet1!A1:D4",
|
|
37
|
+
"updates": {
|
|
38
|
+
"spreadsheetId": bound_spreadsheetid,
|
|
39
|
+
"updatedRange": "Sheet1!A5:D5",
|
|
40
|
+
"updatedRows": 1,
|
|
41
|
+
"updatedColumns": 4,
|
|
42
|
+
"updatedCells": 4,
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def respond(operation: str, request: dict[str, Any]) -> Any:
|
|
48
|
+
"""Dispatch to the fixture for one operation."""
|
|
49
|
+
config: dict[str, Any] = request.get("config") or {}
|
|
50
|
+
fake: FakeValues = request["fake"]
|
|
51
|
+
|
|
52
|
+
if operation == "row_append":
|
|
53
|
+
return _row_append(config, fake)
|
|
54
|
+
|
|
55
|
+
# A faker asked for an operation it has no shape for must SAY so. Making
|
|
56
|
+
# something up would produce a green run whose output silently has none of
|
|
57
|
+
# the fields the author is about to reference.
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f'google_sheets: no fake response is defined for "{operation}". '
|
|
60
|
+
"Add a fixture under provider/fixtures/ and regenerate — a connector without a faker "
|
|
61
|
+
"cannot be developed against, tested, or demonstrated."
|
|
62
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# GENERATED FILE — do not edit.
|
|
2
|
+
#
|
|
3
|
+
# Emitted from provider/manifest.json by weaver's generator.
|
|
4
|
+
# A hand-edit here is destroyed by the next protocol sync, which is worse than
|
|
5
|
+
# being rejected, because it works until it silently does not. Fix
|
|
6
|
+
# provider/manifest.json (or weaver's template/) and regenerate:
|
|
7
|
+
#
|
|
8
|
+
# npm run provider -- google_sheets
|
|
9
|
+
|
|
10
|
+
"""Google Sheets, as one service descriptor shared by every Google Sheets
|
|
11
|
+
operation.
|
|
12
|
+
|
|
13
|
+
The Python twin of the js and php packages' service modules.
|
|
14
|
+
|
|
15
|
+
## The sandbox trap, written down where it is used
|
|
16
|
+
|
|
17
|
+
Google has no sandbox for Sheets. A test spreadsheet is a real one in a real
|
|
18
|
+
Drive, so every append is real -- point this at a scratch sheet, not a
|
|
19
|
+
production one. The faker is the only way to develop against it without
|
|
20
|
+
touching a document.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from ._runtime import PreparedRequest, ServiceDescriptor
|
|
26
|
+
from .faker import respond
|
|
27
|
+
|
|
28
|
+
# The connector API version this package was GENERATED against. A literal,
|
|
29
|
+
# never imported: an imported constant lets an upgrade rewrite the very claim
|
|
30
|
+
# it exists to detect, after which the copy agrees with itself forever.
|
|
31
|
+
CONNECTOR_API_VERSION = 1
|
|
32
|
+
|
|
33
|
+
SERVICE = "google_sheets"
|
|
34
|
+
TITLE = "Google Sheets"
|
|
35
|
+
SANDBOX = "none"
|
|
36
|
+
BASE_URLS = {
|
|
37
|
+
"live": "https://sheets.googleapis.com",
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
"""Credential keys a remote call cannot proceed without."""
|
|
41
|
+
REQUIRES = [
|
|
42
|
+
"accessToken",
|
|
43
|
+
"refreshToken",
|
|
44
|
+
"clientId",
|
|
45
|
+
"clientSecret",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def authorize(
|
|
50
|
+
credentials: dict[str, str | None],
|
|
51
|
+
request: PreparedRequest,
|
|
52
|
+
mode: str,
|
|
53
|
+
) -> None:
|
|
54
|
+
"""Apply Google Sheets's auth scheme to an outgoing request.
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
"""
|
|
58
|
+
request.headers["Authorization"] = f"Bearer {credentials.get('accessToken') or ''}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def descriptor() -> ServiceDescriptor:
|
|
62
|
+
"""The Google Sheets service, for the Python runtime."""
|
|
63
|
+
return ServiceDescriptor(
|
|
64
|
+
service=SERVICE,
|
|
65
|
+
title=TITLE,
|
|
66
|
+
sandbox=SANDBOX,
|
|
67
|
+
base_urls=BASE_URLS,
|
|
68
|
+
requires=REQUIRES,
|
|
69
|
+
authorize=authorize,
|
|
70
|
+
faker=respond,
|
|
71
|
+
idempotency_header=None,
|
|
72
|
+
)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# GENERATED FILE — do not edit.
|
|
2
|
+
#
|
|
3
|
+
# Emitted from provider/fixtures/ by weaver's generator.
|
|
4
|
+
# A hand-edit here is destroyed by the next protocol sync, which is worse than
|
|
5
|
+
# being rejected, because it works until it silently does not. Fix
|
|
6
|
+
# provider/fixtures/ (or weaver's template/) and regenerate:
|
|
7
|
+
#
|
|
8
|
+
# npm run provider -- google_sheets
|
|
9
|
+
|
|
10
|
+
"""The golden fixtures — the SAME values the TypeScript and PHP packages
|
|
11
|
+
assert.
|
|
12
|
+
|
|
13
|
+
Bit-for-bit identical is the claim, and this is what checks it for Python.
|
|
14
|
+
Cross-runtime drift does not fail loudly on its own: it completes, down one
|
|
15
|
+
path, with no error.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import pytest
|
|
19
|
+
|
|
20
|
+
from fancy_google_sheets._fake import FakeValues, seed_for_call
|
|
21
|
+
from fancy_google_sheets.faker import respond
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_row_append_fakes_the_published_shape() -> None:
|
|
25
|
+
config = {}
|
|
26
|
+
fake = FakeValues(seed_for_call("google_sheets", "row_append", config))
|
|
27
|
+
|
|
28
|
+
faked = respond("row_append", {"config": config, "fake": fake})
|
|
29
|
+
|
|
30
|
+
assert faked == {
|
|
31
|
+
"spreadsheetId": "1Sheet_fake_35fe3d32b958",
|
|
32
|
+
"tableRange": "Sheet1!A1:D4",
|
|
33
|
+
"updates": {
|
|
34
|
+
"spreadsheetId": "1Sheet_fake_35fe3d32b958",
|
|
35
|
+
"updatedRange": "Sheet1!A5:D5",
|
|
36
|
+
"updatedRows": 1,
|
|
37
|
+
"updatedColumns": 4,
|
|
38
|
+
"updatedCells": 4,
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_an_operation_with_no_fixture_raises_rather_than_inventing_a_shape() -> None:
|
|
44
|
+
fake = FakeValues(seed_for_call("google_sheets", "no_such_operation", {}))
|
|
45
|
+
|
|
46
|
+
with pytest.raises(ValueError, match="no fake response"):
|
|
47
|
+
respond("no_such_operation", {"config": {}, "fake": fake})
|