# Google Cloud

Google's APIs from the back end, written out in Mote: Cloud Storage,
Sheets, Drive, Calendar, Gmail, Firebase Cloud Messaging (and Apple's push
service beside it), Pub/Sub, BigQuery, Gemini on Vertex AI or the Gemini
API, and Maps. An [extension](../extensions/README.md): ordinary Mote in
`extensions/gcloud/`, a core (`gcloud.mote`) and a file for each service.
Back to the [map](README.md).

```mote
use "pkg:gcloud/sheets.mote"
use "pkg:gcloud/calendar.mote"

shape Lead
  name: string
  email: string
  score: number

// The sales team keeps leads in a sheet by hand; the back end reads them as
// records, and books a call in the signed-in rep's own calendar.
server fn book(sheet: string, accessToken: string): string requires signedIn
  let leads: Lead[] = gcloudSheetsRecords(gcloudAuth([gcloudSheetsScope()]), sheet, "Leads!A:C")?
  let best = leads.toSorted((a, b) => b.score - a.score)[0]
  let rep = gcloudUser(accessToken)
  let e = gcloudCalendarAdd(rep, "primary", {summary: `Call ${best.name}`, start: now() + 86400000, end: now() + 88200000, attendees: [best.email]}, true)?
  return e.link
```

```toml
[packages]
gcloud = "../mote/extensions/gcloud"
mail = "../mote/extensions/mail"   # for gmail.mote
ai = "../mote/extensions/ai"       # for vertex.mote
```

**What was checked.** RS256, which the service account's assertion and
every V4 signed address rest on, against RFC 7515 appendix A.2: its RSA
key signs its signing input to its published signature, byte for byte
(`extensions/gcloud/tests.mote`). Every call against `given net` answers
in that file, and the whole program against a stand-in of Google's APIs
(`tests/svc_gcloud_standin.mjs`, `tests/all.sh real_svc_gcloud`) that
checks the assertion's signature and claims, the access token on every
call, works each V4 signed address out again from the request and refuses
one that differs, checks APNs' ES256 provider token, and speaks HTTP/2
for APNs. Google's own example of a V4 signed URL could not be reproduced
here: its key is not at hand, and nothing may be downloaded. **Nothing has
been asked of Google**: the steps are [below](#checking-it-against-google).

## Who asks

Every call takes a `GcloudAuth` first, so that one fn serves the back end
and a person:

| | |
|---|---|
| `gcloudAuth(scopes)` | The back end: its service account (`GOOGLE_SERVICE_ACCOUNT`), else, on GCP, the metadata server. |
| `gcloudAs(person, scopes)` | The service account acting as a Workspace person (domain-wide delegation, granted in the Admin console for these scopes). |
| `gcloudUser(accessToken)` | A person's own token, from an OAuth sign-in: the oauth extension's `oauthToken(provider, user)`. Not refreshed here. |
| `gcloudKey(key)` | An API key (Maps, the Gemini API). |

A service account's token: a JWT signed RS256 by the key file's private
key (`iss` its address, `scope`, `aud` its token address, an hour,
`sub` for delegation), traded at the token address for an access token,
kept in `GcloudKept` (its token `hidden`) until five minutes before it
ends; a 401 drops it and asks once more. The metadata server's the same,
from `computeMetadata/v1/instance/service-accounts/default/token`.

| Setting | |
|---|---|
| `GOOGLE_SERVICE_ACCOUNT` | The key file's JSON whole: a [secret](back-end.md#secrets) that may be unset (`secret(…, "")`). |
| `GOOGLE_APPLICATION_CREDENTIALS` | Or the file's path. |
| `GOOGLE_PROJECT` | The project; unsaid, the key file's `project_id`. |
| `GCE_METADATA_HOST` | Another address for the metadata server. |
| `GOOGLE_API_URL`, `GOOGLE_API_URL_<SERVICE>` | Another address for every API, or one (`_STORAGE`, `_SHEETS`, `_DRIVE`, `_CALENDAR`, `_GMAIL`, `_FCM`, `_PUBSUB`, `_BIGQUERY`, `_VERTEX`, `_GEMINI`, `_MAPS`, `_PLACES`, `_ROUTES`): a stand-in, an emulator. |
| `GOOGLE_CERTS_URL` | Google's JWKS, for push tokens (its own unsaid). |

| Kind | |
|---|---|
| `"auth"` | No token, or refused (401, 403): Google's status and words follow. |
| `"missing"` | 404. |
| `"conflict"` | 409, 412: it is there already, or a precondition did not hold. |
| `"limited"` | 429, or a 403 for a rate limit, after the tries. |
| `"expired"` | A sync token (Calendar) or a historyId (Gmail) Google no longer keeps: begin again. |
| `"invalid"`, `"google"`, `"offline"` | It refused; it broke (5xx); it did not answer. |

Reads, and writes that are the same done twice, are tried again on 429
and 5xx; an append, an event made, a message sent, a publish are not.

## Cloud Storage

The calls of [s3](s3.md), with who asks first. Settings: `GCS_BUCKET`,
`GCS_CHUNK_SIZE` (8 MiB, a multiple of 256 KiB), `GCS_UPLOADS`.

| Call | |
|---|---|
| `gcloudStoragePut(auth, key, data, type)` | One request (a media upload): a `GcloudObject` (`key`, `size`, `etag`, `type`, `modified`, `generation`). |
| `gcloudStorageUpload(auth, key, data, type)` | Any size: one request, or resumably, piece by piece (each tried again), let go of if one cannot be sent. |
| `gcloudStorageBegin` · `gcloudStoragePiece` | A resumable upload by hand: its session's address (good for a week: it is the upload's whole key), then each piece with its `Content-Range`. |
| `gcloudStorageGet` · `gcloudStorageHead` · `gcloudStorageDelete` · `gcloudStorageList(auth, prefix, most)` | As s3's. |
| `gcloudStorageSignGet(key, seconds, download)` · `gcloudStorageSignPut(key, seconds, type)` | V4 signed addresses (GOOG4-RSA-SHA256), a week at most, signed with the key file's key. |
| `gcloudStorageUploadUrl(name, type)` | A `server fn`: a signed PUT for whoever is signed in, under `uploads/<their id>/`, ten minutes. |
| `gcloudStorageSignV4(key, method, seconds, headers, query, at)` | The signature itself, with its canonical request and string to sign. |

## Sheets, Drive, Calendar, Gmail

| Call | |
|---|---|
| `gcloudSheetsGet` · `Update` · `Append` · `Clear` · `BatchGet` · `BatchUpdate` | Ranges ("Leads!A:C"), read unformatted, written as typed (`USER_ENTERED`). |
| `gcloudSheetsRecords(auth, id, range)` | Rows as records by the header row: `let leads: Lead[] = …`. An empty cell is none, an empty row left out. |
| `gcloudSheetsAppendRecords(auth, id, range, names, records)` | Records added as rows, in the header's order. |
| `gcloudDriveList(auth, q, most, after)` | Drive's query, newest first, a page and its `next`. Shared drives included. |
| `gcloudDriveUpload(auth, name, data, type, parent, as)` | One request (multipart/related); `as` a Google type to convert to. |
| `gcloudDriveDownload(auth, id, as)` · `gcloudDriveDelete` · `gcloudDriveGet` | A Doc exported as `as`. |
| `gcloudDriveShare(auth, id, role, type, who, tell)` · `gcloudDrivePermissions` · `gcloudDriveUnshare` | Who may see it. |
| `gcloudCalendarList(auth, calendar, from, to, after)` | Between two moments, repeats each on its own, by start; its last page has `sync`. |
| `gcloudCalendarChanges(auth, calendar, sync, after)` | What changed since (cancelled ones are deletions); kind `"expired"`: begin again with `""`. |
| `gcloudCalendarAdd` · `Change` · `Delete` | `tell`: Google mails the attendees. |
| `gcloudCalendarBusy(auth, calendars, from, to)` | Free/busy. |
| `gcloudCalendarWatch(auth, calendar, address, days)` · `gcloudCalendarUnwatch` | A channel to `<site>/gcloud/calendar/notify`, its own random token checked on each post (`crypto.equal`); then `fn gcloudCalendarChanged(calendar, channel): bool`, the program's. |
| `mailSend` with `MAIL_PROVIDER=gmail` | Sent as `GMAIL_SENDER` by delegation (`fn gcloudMailAuth(): GcloudAuth` to say otherwise); the MIME message is the mail extension's `mailMime`, its Bcc in the head. |
| `gcloudGmailSend` · `gcloudGmailFind` · `gcloudGmailRead` · `gcloudGmailHistory(auth, historyId)` · `gcloudGmailWatch(auth, topic)` | Sending as anyone a token is for; a mailbox read, and what came since. |

## Pushes: FCM, and APNs beside it

Mote's [notifications](back-end.md#notifications) reach browsers by Web
Push. An app (Android, iOS, a web app on Firebase) gives its token to
`gcloudPushRegister(token, platform)` (an iOS app's own APNs token to
`gcloudApnsRegister(token)`), and a `server fn` does both:

```text
notify.send(user, {title, body, url}, {data, tag})?      the inbox, open pages, Web Push
gcloudPushApps(user, {title, body, url, data, tag})?     each app: FCM, or APNs
```

`notify.send` is only for a `server fn` (`H097`), so the two are two lines,
not one fn. A token FCM says is UNREGISTERED, or APNs answers 410, is
forgotten.

APNs speaks only HTTP/2. **Bun's fetch does not** (Bun 1.2.20 and 1.4.5 fail
against a server that speaks only HTTP/2), so `net.send` has `http2: true`, over
`node:http2`, which apns.mote uses. Without an APNs key, register iOS
tokens with FCM, which has its own APNs key (uploaded in Firebase).
Settings: `APNS_KEY` (the .p8, a secret that may be unset), `APNS_KEY_ID`,
`APNS_TEAM_ID`, `APNS_TOPIC`, `APNS_SANDBOX=1`.

## Pub/Sub, BigQuery, Gemini, Maps

| Call | |
|---|---|
| `gcloudPubsubPublish(auth, topic, messages)` | Each `{data, attributes, key}`: their ids. |
| `gcloudPubsubPull` · `Ack` · `Extend` · `gcloudPubsubPoll(auth, sub, most)` | A pull consumer for a `server every`; `fn gcloudPubsubHandle(subscription, m): bool`, the program's. |
| `/gcloud/pubsub/push` | A push subscription's endpoint: its token checked by Google's keys (kept as long as Google says), its `aud` (`PUBSUB_PUSH_AUDIENCE`) and `email` (`PUBSUB_PUSH_EMAIL`); handled, then 204; else 500, and Pub/Sub sends it again. |
| `gcloudBigqueryQuery(auth, sql, params, most)` | `@name` parameters, never pasted in; waited for; read page by page; cells typed by the schema (numbers, BOOL, TIMESTAMP in milliseconds, RECORD, REPEATED). Mote's own [usage](usage.md) store needs no warehouse; this is for one the company already reads. |
| `gcloudBigqueryInsert(auth, dataset, table, rows)` | Streamed, each with an id (BigQuery's best-effort dedupe): the rows it refused. |
| `AI_PROVIDER=vertex` | The [ai](ai.md) extension's `aiChat`, `aiStreamTo`, `aiRun` on Gemini in Vertex AI: `AI_MODEL`, `VERTEX_LOCATION`, the account's token. (`AI_PROVIDER=gemini`, the Gemini API with `AI_KEY`, is the ai extension's own.) |
| `gcloudGeocode` · `gcloudPlaces` · `gcloudRoute` | Maps, with `GOOGLE_MAPS_KEY`. |

## Unsure

Built from what Google documents as of 2026, without a real answer to
compare: whether a 403 for rate limits still says `rateLimitExceeded` in
every API (Storage and Drive do); Gemini's `functionCall.id` (newer
models give one; an id is made where none is); that Gemini takes a JSON
Schema as `parameters` whole (it takes a subset of OpenAPI's: keep tool
schemas plain); FCM's error for a bad token (UNREGISTERED in `details`, or
400 INVALID_ARGUMENT); the Places and Routes field masks.

## Checking it against Google

Read-only first, in a project of its own:

1. A service account with a JSON key; `GOOGLE_SERVICE_ACCOUNT="$(cat key.json)"`.
   `gcloudToken(gcloudAuth([]))` answers `ya29.…`: the assertion holds.
2. Storage: a bucket, the account `Storage Object Admin` on it.
   `gcloudStorageList(me, "", 10)`, then put, get, head, delete; a 20 MB
   `gcloudStorageUpload` (three pieces at 8 MiB); `gcloudStorageSignGet` in
   a browser, and `curl -X PUT -H 'content-type: image/png'` to a signed PUT.
3. Sheets and Drive: share a sheet with the account's address (reader),
   `gcloudSheetsRecords`; then writer, append. `gcloudDriveList(me, "", 10, "")`.
4. Calendar and Gmail as a person: a Workspace test user, delegation
   granted for the calendar and gmail.send scopes; `gcloudCalendarList` for
   `gcloudAs(user, …)`, then add and delete; `mailSend` with
   `MAIL_PROVIDER=gmail` to yourself.
5. FCM: a Firebase test app's token; `gcloudFcmSend` with the Firebase
   project's account (`Firebase Cloud Messaging API Admin`); then a token
   from an uninstalled app: forgotten. APNs: `APNS_SANDBOX=1` and a
   development build's token.
6. Pub/Sub: a topic, a pull subscription: publish, poll. A push
   subscription with authentication to the deployed site: its log says the
   push was handled.
7. BigQuery: `select 1 as one` (no cost), then a public dataset with a
   parameter; insert into a table of your own.
8. Gemini on Vertex: `AI_PROVIDER=vertex` with the account (`Vertex AI
   User`) and a model. (The Gemini API with an AI Studio key is checked
   in [ai.md](ai.md).)

Recorded in `tests/expect/real_svc_gcloud.txt` (`tests/all.sh
real_svc_gcloud`): the token asked once, each call, a file in three pieces,
a list in two pages, signed addresses used and refused, every service's
calls, a channel's post and a guessed one, an FCM token gone, APNs over
HTTP/2, a push signed by Google and one signed by another key, a query in
two pages, Gemini a turn and one streamed; then the extension's own `mote
test`.
