@tinycloud/sdk-services 3.1.0-beta.7 → 3.1.0-beta.9

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.
package/dist/kv/index.js CHANGED
@@ -5,6 +5,10 @@ var ErrorCodes = {
5
5
  AUTH_EXPIRED: "AUTH_EXPIRED",
6
6
  AUTH_REQUIRED: "AUTH_REQUIRED",
7
7
  AUTH_UNAUTHORIZED: "AUTH_UNAUTHORIZED",
8
+ /** HTTP 401: the delegation the invocation cites was revoked. */
9
+ AUTH_DELEGATION_REVOKED: "AUTH_DELEGATION_REVOKED",
10
+ /** HTTP 401: a delegation the cited one rests on was revoked. */
11
+ AUTH_DELEGATION_ANCESTOR_REVOKED: "AUTH_DELEGATION_ANCESTOR_REVOKED",
8
12
  NETWORK_ERROR: "NETWORK_ERROR",
9
13
  TIMEOUT: "TIMEOUT",
10
14
  ABORTED: "ABORTED",
@@ -16,6 +20,10 @@ var ErrorCodes = {
16
20
  KV_PRECONDITION_FAILED: "KV_PRECONDITION_FAILED",
17
21
  KV_CONFLICT: "KV_CONFLICT",
18
22
  KV_RESPONSE_TOO_LARGE: "KV_RESPONSE_TOO_LARGE",
23
+ /** HTTP 410 from the change feed: discard sync state and restart without a cursor; `meta.reason` says why. */
24
+ KV_SYNC_RESET_REQUIRED: "KV_SYNC_RESET_REQUIRED",
25
+ /** HTTP 403 from the change feed: the retention grant was refused; `meta.reason` says why. */
26
+ KV_RETENTION_GRANT_REFUSED: "KV_RETENTION_GRANT_REFUSED",
19
27
  // SQL-specific errors
20
28
  SQL_ERROR: "SQL_ERROR",
21
29
  SQL_PERMISSION_DENIED: "SQL_PERMISSION_DENIED",
@@ -705,6 +713,30 @@ var PrefixedKVService = class _PrefixedKVService {
705
713
  removePrefix
706
714
  });
707
715
  }
716
+ /**
717
+ * Read the change feed for everything under this prefix. A view with an
718
+ * empty prefix (`""` or `"/"`) is refused: the node does not serve a
719
+ * whole-space feed.
720
+ */
721
+ async changes(options) {
722
+ if (this._prefix.replace(/\/+$/, "") === "") {
723
+ return err(serviceError(
724
+ ErrorCodes.INVALID_INPUT,
725
+ "KV changes needs a non-empty prefix; this view has none",
726
+ "kv"
727
+ ));
728
+ }
729
+ const syncPrefix = `${this._prefix}/`;
730
+ const response = await this._kv.changes({ ...options, prefix: syncPrefix });
731
+ if (!response.ok) return response;
732
+ return ok({
733
+ ...response.data,
734
+ changes: response.data.changes.map((change) => ({
735
+ ...change,
736
+ key: change.key.startsWith(syncPrefix) ? change.key.slice(syncPrefix.length) : change.key
737
+ }))
738
+ });
739
+ }
708
740
  /**
709
741
  * Delete a key.
710
742
  */
@@ -757,11 +789,18 @@ var KVAction = {
757
789
  PUT: "tinycloud.kv/put",
758
790
  LIST: "tinycloud.kv/list",
759
791
  DELETE: "tinycloud.kv/del",
760
- HEAD: "tinycloud.kv/metadata"
792
+ HEAD: "tinycloud.kv/metadata",
793
+ /** The change feed; never implied by `*` or `tinycloud.kv/*`. */
794
+ SYNC: "tinycloud.kv/sync",
795
+ /** Retention attestation; presented through `retentionGrant`, never invoked or implied. */
796
+ RETAIN: "tinycloud.kv/retain"
761
797
  };
762
798
 
763
799
  // src/kv/KVService.ts
764
800
  var MAX_KV_BATCH_READ_ITEMS = 100;
801
+ function isJsonObject(value) {
802
+ return typeof value === "object" && value !== null && !Array.isArray(value);
803
+ }
765
804
  function encodeKvBatchPartName(path) {
766
805
  return encodeURIComponent(path).replace(
767
806
  /[!'()*]/g,
@@ -1680,6 +1719,169 @@ var KVService = class extends BaseService {
1680
1719
  }
1681
1720
  });
1682
1721
  }
1722
+ /**
1723
+ * Read one page of the `tinycloud.kv/sync` change feed for a prefix.
1724
+ */
1725
+ async changes(options) {
1726
+ return this.withTelemetry("changes", options?.prefix, async () => {
1727
+ if (!this.requireAuth()) {
1728
+ return err(authRequiredError("kv"));
1729
+ }
1730
+ if (typeof options?.prefix !== "string" || options.prefix.length === 0) {
1731
+ return err(serviceError(
1732
+ ErrorCodes.INVALID_INPUT,
1733
+ "KV changes prefix must be a non-empty string",
1734
+ "kv"
1735
+ ));
1736
+ }
1737
+ if (options.limit !== void 0 && (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 1e3)) {
1738
+ return err(serviceError(
1739
+ ErrorCodes.INVALID_INPUT,
1740
+ "KV changes limit must be an integer from 1 through 1000",
1741
+ "kv"
1742
+ ));
1743
+ }
1744
+ const headers = {};
1745
+ if (options.limit !== void 0) headers["x-tinycloud-limit"] = String(options.limit);
1746
+ if (options.cursor !== void 0) headers["x-tinycloud-cursor"] = options.cursor;
1747
+ if (options.retentionGrant !== void 0) {
1748
+ headers["x-tinycloud-retention-grant"] = options.retentionGrant;
1749
+ }
1750
+ const request = this.createRequestSignal(options.signal, options.timeout);
1751
+ try {
1752
+ const response = await this.invokeOperation(
1753
+ options.prefix,
1754
+ KVAction.SYNC,
1755
+ void 0,
1756
+ request.signal,
1757
+ headers
1758
+ );
1759
+ if (!response.ok) {
1760
+ return await this.changesFailure(response, options.prefix, request.signal);
1761
+ }
1762
+ const text = await response.text();
1763
+ let body;
1764
+ try {
1765
+ body = JSON.parse(text);
1766
+ } catch {
1767
+ body = void 0;
1768
+ }
1769
+ const page = this.normalizeChangesResponse(body);
1770
+ if (!page) {
1771
+ return err(serviceError(
1772
+ ErrorCodes.NETWORK_ERROR,
1773
+ "KV changes response was not a tinycloud.kv/sync page",
1774
+ "kv",
1775
+ { meta: { status: response.status, statusText: response.statusText } }
1776
+ ));
1777
+ }
1778
+ return ok(page);
1779
+ } catch (error) {
1780
+ return err(wrapError("kv", error));
1781
+ } finally {
1782
+ request.dispose();
1783
+ }
1784
+ });
1785
+ }
1786
+ /**
1787
+ * Map a failed `kv/sync` response. 410 and the retention 403 carry
1788
+ * `{"error":{"code","reason"}}`; a revoked grant is a 401 whose text names
1789
+ * `delegation-revoked` or `delegation-ancestor-revoked`. A body read that
1790
+ * fails because the request was cancelled or timed out rethrows, so the
1791
+ * caller sees `ABORTED`/`TIMEOUT` rather than a mapped status.
1792
+ */
1793
+ async changesFailure(response, prefix, signal) {
1794
+ if (response.status === 404) {
1795
+ return this.classifyNotFound(response, prefix);
1796
+ }
1797
+ let errorText;
1798
+ try {
1799
+ errorText = await response.text();
1800
+ } catch (error) {
1801
+ if (signal.aborted) throw error;
1802
+ errorText = "";
1803
+ }
1804
+ const meta = { status: response.status, statusText: response.statusText };
1805
+ let reason;
1806
+ let bodyCode;
1807
+ try {
1808
+ const body = JSON.parse(errorText);
1809
+ const error = isJsonObject(body) ? body.error : void 0;
1810
+ if (isJsonObject(error)) {
1811
+ if (typeof error.code === "string") bodyCode = error.code;
1812
+ if (typeof error.reason === "string") reason = error.reason;
1813
+ }
1814
+ } catch {
1815
+ }
1816
+ const context = `Failed to read KV changes for ${JSON.stringify(prefix)}`;
1817
+ if (response.status === 410) {
1818
+ return err(serviceError(
1819
+ ErrorCodes.KV_SYNC_RESET_REQUIRED,
1820
+ `${context}: the node requires a reset (${reason ?? "reason not given"}); discard sync state and restart without a cursor`,
1821
+ "kv",
1822
+ { meta: { ...meta, reason } }
1823
+ ));
1824
+ }
1825
+ if (response.status === 403 && bodyCode === "RETENTION_GRANT_REFUSED") {
1826
+ return err(serviceError(
1827
+ ErrorCodes.KV_RETENTION_GRANT_REFUSED,
1828
+ `${context}: the retention grant was refused (${reason ?? "reason not given"})`,
1829
+ "kv",
1830
+ { meta: { ...meta, reason } }
1831
+ ));
1832
+ }
1833
+ if (response.status === 401) {
1834
+ const revoked = /\bdelegation-ancestor-revoked\b/.test(errorText) ? ErrorCodes.AUTH_DELEGATION_ANCESTOR_REVOKED : /\bdelegation-revoked\b/.test(errorText) ? ErrorCodes.AUTH_DELEGATION_REVOKED : void 0;
1835
+ if (revoked !== void 0) {
1836
+ return err(serviceError(revoked, `${context}: 401 - ${errorText}`, "kv", { meta }));
1837
+ }
1838
+ }
1839
+ if (response.status === 401 || response.status === 403) {
1840
+ return this.authorizationFailure(context, response, errorText, [prefix], KVAction.SYNC);
1841
+ }
1842
+ return err(serviceError(
1843
+ response.status === 400 ? ErrorCodes.INVALID_INPUT : ErrorCodes.NETWORK_ERROR,
1844
+ `${context}: ${response.status} - ${errorText}`,
1845
+ "kv",
1846
+ { meta }
1847
+ ));
1848
+ }
1849
+ normalizeChangesResponse(data) {
1850
+ if (!isJsonObject(data)) return void 0;
1851
+ const { changes, more, cursor, source, authority } = data;
1852
+ if (!Array.isArray(changes) || typeof more !== "boolean" || typeof cursor !== "string" || !isJsonObject(source) || typeof source.nodeDid !== "string" || typeof source.space !== "string" || typeof source.prefix !== "string" || !isJsonObject(authority)) {
1853
+ return void 0;
1854
+ }
1855
+ const { notBefore, expiresAt, retainUntil } = authority;
1856
+ if (notBefore !== null && typeof notBefore !== "string" || expiresAt !== null && typeof expiresAt !== "string" || retainUntil !== null && typeof retainUntil !== "string") {
1857
+ return void 0;
1858
+ }
1859
+ const parsed = [];
1860
+ for (const change of changes) {
1861
+ if (!isJsonObject(change) || typeof change.key !== "string") return void 0;
1862
+ if (change.deleted === true) {
1863
+ parsed.push({ key: change.key, deleted: true });
1864
+ continue;
1865
+ }
1866
+ const { metadata } = change;
1867
+ if (change.deleted !== false || typeof change.etag !== "string" || !isJsonObject(metadata) || !Object.values(metadata).every((value) => typeof value === "string")) {
1868
+ return void 0;
1869
+ }
1870
+ parsed.push({
1871
+ key: change.key,
1872
+ deleted: false,
1873
+ etag: change.etag,
1874
+ metadata
1875
+ });
1876
+ }
1877
+ return {
1878
+ changes: parsed,
1879
+ more,
1880
+ cursor,
1881
+ source: { nodeDid: source.nodeDid, space: source.space, prefix: source.prefix },
1882
+ authority: { notBefore, expiresAt, retainUntil }
1883
+ };
1884
+ }
1683
1885
  /**
1684
1886
  * Delete a key.
1685
1887
  */