Cotton code
466 lines · 25.1 KB · TypeScriptRaw
/** * PUBLISHED DATABASES (owner, 14 Nov 2026): reference rows anyone signed in to * Cotton may read and nobody but their publisher may write. A person's own * database is private and lives in its Business object; a published one lives * in a `Published` object of its own, one per `<publisher>/<name>`, SQLite * inside it. Cotton is the first publisher (cities, holidays, airports, English * words, from `scripts/datasets/`); the shape leaves room for others: a * publisher, a name and a version name every row, and a publisher's token is * one entry in the PUBLISHER_TOKENS secret. No publishing UI, no sign-up and no * listing exist yet. * * WHY A DURABLE OBJECT WITH SQLITE (not D1, not SQLite in R2): the platform is * one Worker with Durable Objects and no D1 ([cotton-is-a-platform-on-one-core…]); * an object holds the whole ~70 MB cities set well inside its 10 GB, answers an * indexed prefix read in a millisecond or two once warm, and a cold start loads * pages lazily rather than the whole file. SQLite in R2 read by range would pay * a round trip to R2 per page touched (an index walk is several), and has no * write path. Cost: storage at the object rate is cents a month; a publish is a * write per row and per search key (a few million rows for places), a read is * a few index rows. * *   POST /v1/published/<publisher>/<name>/<table>/search   any signed-in device *        { q, prefer?, limit? }        rows whose names start with q (two characters at least): those *                                      whose own name does first, then the prefer group's, then by rank *        { near: {lat, lng}, limit? }  the nearest rows *        { ids: [id, …], version? }    those rows, at the current version or one still held *     → 200 { publisher, name, table, version, rows: [{ id, …, lat?, lng? }] } *   GET  /v1/published/<publisher>/<name>                 any signed-in device *     → 200 { publisher, name, version, tables: { <table>: rows } } * *   The publisher's own, bearer = that publisher's token and nothing else: *   PUT  /v1/published/<publisher>/<name>/versions/<version>          begin (or restart) loading *   POST /v1/published/<publisher>/<name>/versions/<version>/rows     { table, rows: [{ id, row, names?, lat?, lng?, rank?, group? }] } *   POST /v1/published/<publisher>/<name>/versions/<version>/commit   the version becomes current * * A SEARCH IS A POST so what a person types never sits in a URL, which is what * request logs keep; nothing here logs a body. The edge cache is keyed by a * hash of the ask, never by its words. Each signed-in database is held to * LIMITS.perMinute reads (the PUBLISHED_READS rate limit binding), counted and * never kept. */import { DurableObject } from "cloudflare:workers";import type { Env } from "./env.ts";import { json, Refused, refuse, sha256Hex } from "./http.ts";export const PATH = /^\/v1\/published\/([a-z][a-z0-9-]{1,40})\/([a-z][a-z0-9_-]{1,40})(?:\/(.*))?$/;const TABLE = /^[a-z][a-z0-9_]{0,40}$/;const VERSION = /^[0-9A-Za-z][0-9A-Za-z._-]{0,40}$/;const ID = /^\P{Cc}{1,200}$/u;export const LIMITS = {  /** Reads a signed-in database may make in a minute (wrangler.jsonc `ratelimits`). */  perMinute: 600,  rowsPerWrite: 5000,  writeBytes: 8 * 1024 * 1024,  searchBytes: 4096,  ids: 100,  results: 50,  /** Shortest search, in characters after normalising. */  shortest: 2,};/** How long a search's answer is kept at the edge and on the phone. */const SEARCH_SECONDS = 3600;/** A device credential's vouch, kept in this isolate so a keystroke is not a second object's read. */const VOUCH_MS = 10 * 60 * 1000;const vouched = new Map<string, number>();/** One published row as its publisher sends it. */export interface RowIn {  id: string;  row: Record<string, unknown>;  names?: string[];  lat?: number;  lng?: number;  rank?: number;  group?: string;}/** What a read asks. */export type Ask =  | { kind: "search"; table: string; q: string; prefer: string | null; limit: number }  | { kind: "near"; table: string; lat: number; lng: number; limit: number }  | { kind: "ids"; table: string; ids: string[]; version: string | null };export interface Answer {  publisher: string;  name: string;  table?: string;  version: string;  rows?: Record<string, unknown>[];  tables?: Record<string, number>;}/** An answer that crosses RPC whole: a refusal is a status and words, never a thrown error. */export type Answered = { ok: Answer } | { refused: { status: number; code: string; message: string } };/** * The search key every name is held under and every ask is read with: no * case, no accents, words split on anything that is not a letter or a digit. */export function searchKey(text: string): string {  return text    .normalize("NFKD")    .replace(/\p{M}+/gu, "")    .toLowerCase()    .replace(/[^\p{L}\p{N}]+/gu, " ")    .trim();}/** Every key a name is found by: the whole name, and the name from each later word on ("new york", "york"). */export function keysOf(names: string[]): string[] {  const keys = new Set<string>();  for (const name of names) {    const key = searchKey(name);    if (!key) continue;    const words = key.split(" ");    for (let n = 0; n < words.length; n += 1) keys.add(words.slice(n).join(" ").slice(0, 120));  }  return [...keys];}// ── the door (src/open.ts) ───────────────────────────────────────────────interface Doors {  token: string | null;  /** The database a device credential names, or null. */  databaseOf(token: string): string | null;  /** Whether that database's object vouches for the credential. */  vouch(databaseId: string, token: string): Promise<boolean>;}export async function door(request: Request, env: Env, path: string, doors: Doors): Promise<Response> {  const named = PATH.exec(path);  if (!named) refuse(404, "not_found", "no such published database");  const publisher = named[1]!;  const name = named[2]!;  const rest = named[3] ?? "";  const written = /^versions\/([^/]+)(?:\/(rows|commit))?$/.exec(rest);  if (written) return write(request, env, doors.token, publisher, name, written[1]!, written[2] ?? null);  const databaseId = await reader(doors);  const limited = await env.PUBLISHED_READS.limit({ key: databaseId });  if (!limited.success) refuse(429, "slow_down", "too many reads of published databases this minute; try again in a moment");  if (rest === "" && request.method === "GET") return answer(await stub(env, publisher, name).about(publisher, name));  const searched = /^([^/]+)\/search$/.exec(rest);  if (!searched || request.method !== "POST") refuse(404, "not_found", "no such published route");  const table = searched[1]!;  if (!TABLE.test(table)) refuse(400, "bad_table", "name a table of the published database");  const ask = askOf(table, await bodyOf(request, LIMITS.searchBytes));  // The edge cache, keyed by a hash of the ask: what was typed is in no key.  const cache = caches.default;  const key = new Request(`https://published.cache/${publisher}/${name}/${table}/${await sha256Hex(JSON.stringify(ask))}`);  const held = await cache.match(key);  if (held) return held;  const fresh = answer(await stub(env, publisher, name).read(publisher, name, ask), ask.kind === "ids" && ask.version ? 86400 : SEARCH_SECONDS);  if (fresh.status === 200) await cache.put(key, fresh.clone());  return fresh;}/** The signed-in database a read comes from: a device credential its own object vouches for. */async function reader(doors: Doors): Promise<string> {  const token = doors.token;  const databaseId = token ? doors.databaseOf(token) : null;  if (!token || !databaseId) refuse(401, "no_database", "sign in to Cotton to read published databases");  const hash = await sha256Hex(token);  const until = vouched.get(hash);  if (until && until > Date.now()) return databaseId;  if (!(await doors.vouch(databaseId, token))) refuse(401, "invalid_credential", "sign in again");  if (vouched.size > 50_000) vouched.clear();  vouched.set(hash, Date.now() + VOUCH_MS);  return databaseId;}/** The publisher's write: their token alone, compared whole. Nothing of a person's ever passes here. */async function write(request: Request, env: Env, token: string | null, publisher: string, name: string, version: string, step: string | null): Promise<Response> {  const expected = publisherToken(env, publisher);  if (!expected || !token || !(await same(token, expected))) refuse(403, "publisher_only", "only this database's publisher writes it");  if (!VERSION.test(version)) refuse(400, "bad_version", "a version is letters, digits, dots and dashes");  const object = stub(env, publisher, name);  if (step === null && request.method === "PUT") return answer(await object.begin(publisher, name, version));  if (step === "commit" && request.method === "POST") return answer(await object.commit(publisher, name, version));  if (step === "rows" && request.method === "POST") {    const body = await bodyOf(request, LIMITS.writeBytes);    const table = typeof body.table === "string" && TABLE.test(body.table) ? body.table : refuse(400, "bad_table", "table: the published table these rows belong to");    const rows = Array.isArray(body.rows) ? body.rows : refuse(400, "bad_rows", "rows: a list");    if (rows.length > LIMITS.rowsPerWrite) refuse(413, "too_many_rows", `at most ${LIMITS.rowsPerWrite} rows a write`);    return answer(await object.load(publisher, name, version, table, rows.map(rowIn)));  }  refuse(404, "not_found", "no such publishing route");}function publisherToken(env: Env, publisher: string): string | null {  if (!env.PUBLISHER_TOKENS) return null;  let tokens: unknown;  try {    tokens = JSON.parse(env.PUBLISHER_TOKENS);  } catch {    return null;  }  const token = tokens && typeof tokens === "object" ? (tokens as Record<string, unknown>)[publisher] : null;  return typeof token === "string" && token.length >= 32 ? token : null;}async function same(a: string, b: string): Promise<boolean> {  const [x, y] = await Promise.all([sha256Hex(a), sha256Hex(b)]);  let diff = 0;  for (let n = 0; n < x.length; n += 1) diff |= x.charCodeAt(n) ^ y.charCodeAt(n);  return diff === 0;}async function bodyOf(request: Request, cap: number): Promise<Record<string, unknown>> {  const declared = Number(request.headers.get("content-length") ?? "0");  if (declared > cap) refuse(413, "too_large", `at most ${cap} bytes`);  const raw = await request.arrayBuffer().catch(() => refuse(400, "bad_request", "the body could not be read"));  if (raw.byteLength > cap) refuse(413, "too_large", `at most ${cap} bytes`);  let body: unknown;  try {    body = JSON.parse(new TextDecoder().decode(raw));  } catch {    refuse(400, "bad_json", "the body is not JSON");  }  if (!body || typeof body !== "object" || Array.isArray(body)) refuse(400, "bad_request", "the body is a JSON object");  return body as Record<string, unknown>;}function askOf(table: string, body: Record<string, unknown>): Ask {  const limit = Math.min(Math.max(Number.isInteger(body.limit) ? (body.limit as number) : 8, 1), LIMITS.results);  if (Array.isArray(body.ids)) {    const ids = body.ids.filter((id): id is string => typeof id === "string" && ID.test(id));    if (!ids.length || ids.length !== body.ids.length || ids.length > LIMITS.ids) refuse(400, "bad_ids", `ids: one to ${LIMITS.ids} row ids`);    const version = body.version === undefined || body.version === null ? null : typeof body.version === "string" && VERSION.test(body.version) ? body.version : refuse(400, "bad_version", "version: a version name");    return { kind: "ids", table, ids: [...new Set(ids)].sort(), version };  }  if (body.near !== undefined) {    const near = body.near as { lat?: unknown; lng?: unknown } | null;    const lat = Number(near?.lat);    const lng = Number(near?.lng);    if (!Number.isFinite(lat) || !Number.isFinite(lng) || Math.abs(lat) > 90 || Math.abs(lng) > 180) refuse(400, "bad_coordinates", "near: {lat, lng} on Earth");    // Rounded to about a hundred metres: the nearest town does not move for less, and the cache holds fewer keys.    return { kind: "near", table, lat: Math.round(lat * 1000) / 1000, lng: Math.round(lng * 1000) / 1000, limit };  }  const q = typeof body.q === "string" ? searchKey(body.q).slice(0, 120) : refuse(400, "bad_query", "q: the words to search, or near, or ids");  if ([...q].length < LIMITS.shortest) refuse(400, "short_query", `a search is at least ${LIMITS.shortest} letters`);  const prefer = typeof body.prefer === "string" && body.prefer.length <= 40 ? body.prefer : null;  return { kind: "search", table, q, prefer, limit };}function rowIn(value: unknown): RowIn {  const r = value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : refuse(400, "bad_row", "a row is an object");  const id = typeof r.id === "string" && ID.test(r.id) ? r.id : refuse(400, "bad_row", "a row needs its id");  const row = r.row && typeof r.row === "object" && !Array.isArray(r.row) ? (r.row as Record<string, unknown>) : refuse(400, "bad_row", `row ${id}: its fields as an object`);  const names = r.names === undefined ? [] : Array.isArray(r.names) && r.names.every((n) => typeof n === "string") ? (r.names as string[]) : refuse(400, "bad_row", `row ${id}: names is a list of words`);  const number = (v: unknown, what: string, bound: number): number | undefined => (v === undefined || v === null ? undefined : typeof v === "number" && Number.isFinite(v) && Math.abs(v) <= bound ? v : refuse(400, "bad_row", `row ${id}: ${what}`));  const lat = number(r.lat, "lat", 90);  const lng = number(r.lng, "lng", 180);  if ((lat === undefined) !== (lng === undefined)) refuse(400, "bad_row", `row ${id}: lat and lng together`);  const rank = number(r.rank, "rank", Number.MAX_SAFE_INTEGER);  const group = r.group === undefined || r.group === null ? undefined : typeof r.group === "string" && r.group.length <= 40 ? r.group : refuse(400, "bad_row", `row ${id}: group`);  return { id, row, names, lat, lng, rank, group };}function answer(answered: Answered, seconds = 0): Response {  if ("refused" in answered) return json({ code: answered.refused.code, message: answered.refused.message }, answered.refused.status);  return json(answered.ok, 200, seconds ? { "cache-control": `private, max-age=${seconds}` } : {});}function stub(env: Env, publisher: string, name: string): DurableObjectStub<Published> {  return env.PUBLISHED.get(env.PUBLISHED.idFromName(`${publisher}/${name}`), { locationHint: "apac" });}// ── the object ───────────────────────────────────────────────────────────const SCHEMA = `CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);CREATE TABLE IF NOT EXISTS version (version TEXT PRIMARY KEY, state TEXT NOT NULL, made_at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS shelf (sid INTEGER PRIMARY KEY, version TEXT NOT NULL, tbl TEXT NOT NULL, UNIQUE (version, tbl));CREATE TABLE IF NOT EXISTS row (rid INTEGER PRIMARY KEY, sid INTEGER NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL, lead TEXT NOT NULL DEFAULT '', lat REAL, lng REAL, rank REAL NOT NULL DEFAULT 0, grp TEXT);CREATE UNIQUE INDEX IF NOT EXISTS row_id ON row (sid, id);CREATE INDEX IF NOT EXISTS row_lat ON row (sid, lat) WHERE lat IS NOT NULL;CREATE TABLE IF NOT EXISTS term (sid INTEGER NOT NULL, key TEXT NOT NULL, rid INTEGER NOT NULL, PRIMARY KEY (sid, key, rid)) WITHOUT ROWID;`;// A shelf is one table at one version, named by a small number so the// millions of search keys carry no repeated words (a places set's keys are// most of its bytes)./** How many versions a database keeps: the current one, and the one before for a phone mid-pick. */const KEPT_VERSIONS = 2;export class Published extends DurableObject<Env> {  private sql: SqlStorage;  constructor(ctx: DurableObjectState, env: Env) {    super(ctx, env);    this.sql = ctx.storage.sql;    this.sql.exec(SCHEMA);  }  async about(publisher: string, name: string): Promise<Answered> {    return this.answering(() => this.aboutNow(publisher, name));  }  async read(publisher: string, name: string, ask: Ask): Promise<Answered> {    return this.answering(() => {      let version = this.current(publisher, name);      if (ask.kind === "ids" && ask.version && ask.version !== version) {        const held = this.sql.exec<{ state: string }>("SELECT state FROM version WHERE version=?", ask.version).toArray()[0];        if (!held || held.state === "loading") refuse(410, "version_gone", "that version is no longer published; read the current one");        version = ask.version;      }      const rows = ask.kind === "search" ? this.search(version, ask) : ask.kind === "near" ? this.near(version, ask) : this.byIds(version, ask);      return { publisher, name, table: ask.table, version, rows };    });  }  async begin(publisher: string, name: string, version: string): Promise<Answered> {    return this.answering(() => {      this.own(publisher, name);      const held = this.sql.exec<{ state: string }>("SELECT state FROM version WHERE version=?", version).toArray()[0];      if (held && held.state !== "loading") refuse(409, "version_published", "that version is already published; publish a new version");      this.ctx.storage.transactionSync(() => {        this.drop(version);        this.sql.exec("INSERT INTO version (version, state, made_at) VALUES (?, 'loading', ?)", version, Date.now());      });      return { publisher, name, version };    });  }  async load(publisher: string, name: string, version: string, table: string, rows: RowIn[]): Promise<Answered> {    return this.answering(() => {      this.own(publisher, name);      const held = this.sql.exec<{ state: string }>("SELECT state FROM version WHERE version=?", version).toArray()[0];      if (held?.state !== "loading") refuse(409, "not_loading", "begin the version before loading rows into it");      this.ctx.storage.transactionSync(() => {        const sid = this.shelf(version, table, true)!;        for (const r of rows) {          // A row already loaded is a retried write whose answer was lost: kept as it is.          if (this.sql.exec("SELECT 1 FROM row WHERE sid=? AND id=?", sid, r.id).toArray().length) continue;          const rid = this.sql            .exec<{ rid: number }>("INSERT INTO row (sid, id, body, lead, lat, lng, rank, grp) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING rid", sid, r.id, JSON.stringify({ ...r.row, id: r.id }), searchKey(r.names?.[0] ?? ""), r.lat ?? null, r.lng ?? null, r.rank ?? 0, r.group ?? null)            .one().rid;          for (const key of keysOf(r.names ?? [])) this.sql.exec("INSERT OR IGNORE INTO term (sid, key, rid) VALUES (?, ?, ?)", sid, key, rid);        }      });      return { publisher, name, version, table, rows: [] };    });  }  async commit(publisher: string, name: string, version: string): Promise<Answered> {    return this.answering(() => {      this.own(publisher, name);      const held = this.sql.exec<{ state: string }>("SELECT state FROM version WHERE version=?", version).toArray()[0];      if (!held) refuse(404, "no_version", "that version was never begun");      this.ctx.storage.transactionSync(() => {        this.sql.exec("UPDATE version SET state='retired' WHERE state='current'");        this.sql.exec("UPDATE version SET state='current' WHERE version=?", version);        this.sql.exec("INSERT INTO meta (key, value) VALUES ('version', ?) ON CONFLICT (key) DO UPDATE SET value=excluded.value", version);        const kept = this.sql.exec<{ version: string }>("SELECT version FROM version WHERE state!='loading' ORDER BY (state='current') DESC, made_at DESC").toArray().slice(KEPT_VERSIONS);        for (const old of kept) {          this.drop(old.version);          this.sql.exec("DELETE FROM version WHERE version=?", old.version);        }      });      return this.aboutNow(publisher, name);    });  }  private aboutNow(publisher: string, name: string): Answer {    const version = this.current(publisher, name);    const tables: Record<string, number> = {};    for (const r of this.sql.exec<{ tbl: string; n: number }>("SELECT s.tbl, COUNT(r.rid) AS n FROM shelf s JOIN row r ON r.sid=s.sid WHERE s.version=? GROUP BY s.tbl ORDER BY s.tbl", version)) tables[r.tbl] = r.n;    return { publisher, name, version, tables };  }  private search(version: string, ask: Extract<Ask, { kind: "search" }>): Record<string, unknown>[] {    const sid = this.shelf(version, ask.table, false);    if (sid === null) return [];    const rows = this.sql.exec<{ body: string; lat: number | null; lng: number | null }>(      `SELECT r.body, r.lat, r.lng FROM row r       WHERE r.rid IN (SELECT rid FROM term WHERE sid=?1 AND key>=?2 AND key<?3)       ORDER BY (r.lead>=?2 AND r.lead<?3) DESC, (r.grp IS NOT NULL AND r.grp=?4) DESC, r.rank DESC, r.id LIMIT ?5`,      sid, ask.q, `${ask.q}\uffff`, ask.prefer ?? "", ask.limit,    );    return [...rows].map(rowOut);  }  /**   * The nearest rows: a box around the point, widened until the nearest row   * found is no farther than the box reaches, so nothing outside it is nearer.   */  private near(version: string, ask: Extract<Ask, { kind: "near" }>): Record<string, unknown>[] {    const sid = this.shelf(version, ask.table, false);    if (sid === null) return [];    for (const degrees of [0.5, 2, 8, 32, 180]) {      const south = ask.lat - degrees;      const north = ask.lat + degrees;      const widest = Math.max(Math.abs(south), Math.abs(north));      const spread = widest >= 89.9 ? 180 : Math.min(180, degrees / Math.cos((widest * Math.PI) / 180));      const found = [...this.sql.exec<{ body: string; lat: number; lng: number }>("SELECT body, lat, lng FROM row WHERE sid=? AND lat BETWEEN ? AND ?", sid, south, north)]        .filter((r) => spread >= 180 || Math.abs(((r.lng - ask.lng + 540) % 360) - 180) <= spread)        .map((r) => ({ r, arc: arcDegrees(ask.lat, ask.lng, r.lat, r.lng) }))        .sort((a, b) => a.arc - b.arc);      if (found.length && (found[Math.min(ask.limit, found.length) - 1]!.arc <= degrees || degrees === 180)) return found.slice(0, ask.limit).map(({ r }) => rowOut(r));    }    return [];  }  private byIds(version: string, ask: Extract<Ask, { kind: "ids" }>): Record<string, unknown>[] {    const sid = this.shelf(version, ask.table, false);    if (sid === null) return [];    // One JSON parameter, not one per id: the object's SQLite binds at most 100, and a read may ask for 100 ids beside the shelf.    return [...this.sql.exec<{ body: string; lat: number | null; lng: number | null }>("SELECT body, lat, lng FROM row WHERE sid=? AND id IN (SELECT value FROM json_each(?)) ORDER BY id", sid, JSON.stringify(ask.ids))].map(rowOut);  }  /** A table's shelf at a version, made when loading asks for it. */  private shelf(version: string, table: string, make: boolean): number | null {    const held = this.sql.exec<{ sid: number }>("SELECT sid FROM shelf WHERE version=? AND tbl=?", version, table).toArray()[0];    if (held || !make) return held?.sid ?? null;    return this.sql.exec<{ sid: number }>("INSERT INTO shelf (version, tbl) VALUES (?, ?) RETURNING sid", version, table).one().sid;  }  private current(publisher: string, name: string): string {    this.own(publisher, name);    const version = this.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key='version'").toArray()[0]?.value;    if (!version) refuse(404, "not_published", `${publisher}/${name} has no published version yet`);    return version;  }  /** The object is named by `<publisher>/<name>` and keeps the names it was first asked under. */  private own(publisher: string, name: string): void {    const held = this.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key='database'").toArray()[0]?.value;    const asked = `${publisher}/${name}`;    if (held === undefined) this.sql.exec("INSERT INTO meta (key, value) VALUES ('database', ?)", asked);    else if (held !== asked) refuse(500, "wrong_object", "this object holds another published database");  }  private drop(version: string): void {    for (const { sid } of this.sql.exec<{ sid: number }>("SELECT sid FROM shelf WHERE version=?", version).toArray()) {      this.sql.exec("DELETE FROM term WHERE sid=?", sid);      this.sql.exec("DELETE FROM row WHERE sid=?", sid);    }    this.sql.exec("DELETE FROM shelf WHERE version=?", version);  }  private answering(work: () => Answer): Answered {    try {      return { ok: work() };    } catch (error) {      if (error instanceof Refused) return { refused: { status: error.status, code: error.code, message: error.message } };      throw error;    }  }}function rowOut(r: { body: string; lat: number | null; lng: number | null }): Record<string, unknown> {  const body = JSON.parse(r.body) as Record<string, unknown>;  return r.lat === null ? body : { ...body, lat: r.lat, lng: r.lng };}/** The angle between two points on the sphere, in degrees. */function arcDegrees(lat1: number, lng1: number, lat2: number, lng2: number): number {  const rad = Math.PI / 180;  const cos = Math.sin(lat1 * rad) * Math.sin(lat2 * rad) + Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * Math.cos((lng1 - lng2) * rad);  return Math.acos(Math.min(1, Math.max(-1, cos))) / rad;}