@datafn/server 0.1.1 → 0.1.4-maint.0

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/README.md CHANGED
@@ -37,34 +37,6 @@ permission-directory projection. See
37
37
  for configuration, error, WebSocket, consistency, migration, and operations
38
38
  contracts.
39
39
 
40
- ### Initial region placement
41
-
42
- DataFn provides reusable region selection without embedding a product's data
43
- residency or capacity policy:
44
-
45
- ```typescript
46
- import {
47
- readDatafnCloudflarePlacementLocation,
48
- selectDatafnPlacementRegion,
49
- } from "@datafn/server/placement";
50
-
51
- const decision = selectDatafnPlacementRegion({
52
- candidates: regions,
53
- location: readDatafnCloudflarePlacementLocation(request),
54
- constraints: [
55
- (region) => allowedRegionIds.includes(region.regionId),
56
- (region) => healthyRegionIds.has(region.regionId),
57
- ],
58
- });
59
- ```
60
-
61
- An eligible explicit preference wins first, trusted coordinates or continent
62
- metadata rank the remaining regions by distance, and an optional `stableKey`
63
- enables deterministic fallback. The returned decision records which source was
64
- used. Applications remain responsible for defining eligible regions, collecting
65
- explicit organization choices, and atomically claiming the resulting namespace
66
- through the placement directory.
67
-
68
40
  ---
69
41
 
70
42
  ## Quick Start
package/dist/index.cjs CHANGED
@@ -8154,8 +8154,9 @@ async function recordChangesWithRetry(changeTracking, entries, maxRetries = 2, l
8154
8154
  }
8155
8155
  }
8156
8156
  }
8157
+ var preparedNamespaces = /* @__PURE__ */ new WeakMap();
8157
8158
  var ChangeTrackingService = class _ChangeTrackingService {
8158
- constructor(db, namespace = "datafn", sequenceStore, onChange, logger, metaEnsured = false, changesEnsured = false) {
8159
+ constructor(db, namespace = "datafn", sequenceStore, onChange, logger, metaEnsured = false, changesEnsured = false, namespaceMetaEnsured = false) {
8159
8160
  this.db = db;
8160
8161
  this.namespace = namespace;
8161
8162
  this.sequenceStore = sequenceStore;
@@ -8163,8 +8164,10 @@ var ChangeTrackingService = class _ChangeTrackingService {
8163
8164
  this.logger = logger;
8164
8165
  this.metaEnsured = false;
8165
8166
  this.changesEnsured = false;
8167
+ this.namespaceMetaEnsured = false;
8166
8168
  this.metaEnsured = metaEnsured;
8167
8169
  this.changesEnsured = changesEnsured;
8170
+ this.namespaceMetaEnsured = namespaceMetaEnsured;
8168
8171
  }
8169
8172
  /** Initialize every durable table before an enclosing transaction begins. */
8170
8173
  async ensureReady() {
@@ -8179,6 +8182,48 @@ var ChangeTrackingService = class _ChangeTrackingService {
8179
8182
  await ensureInternalTable(this.db, "__datafn_meta");
8180
8183
  this.metaEnsured = true;
8181
8184
  }
8185
+ await this.ensureNamespaceMeta();
8186
+ }
8187
+ /**
8188
+ * Creates this namespace's `__datafn_meta` row before an enclosing
8189
+ * transaction begins. Sequence allocation otherwise creates the row inside
8190
+ * the transaction on a namespace's first write, and when two first writes
8191
+ * race, the losing INSERT fails with a unique-key conflict. On PostgreSQL that
8192
+ * aborts the whole transaction, so the recovery read that follows fails with
8193
+ * "current transaction is aborted". Outside a transaction the conflict is
8194
+ * harmless: the row exists either way, and later allocations only read and
8195
+ * CAS-update it. Transaction-bound instances (from `withDb`) never prepare
8196
+ * the row; the base instance does so before the transaction opens.
8197
+ */
8198
+ async ensureNamespaceMeta() {
8199
+ if (this.namespaceMetaEnsured) {
8200
+ return;
8201
+ }
8202
+ let prepared = preparedNamespaces.get(this.db);
8203
+ if (!prepared) {
8204
+ prepared = /* @__PURE__ */ new Set();
8205
+ preparedNamespaces.set(this.db, prepared);
8206
+ }
8207
+ if (prepared.has(this.namespace)) {
8208
+ this.namespaceMetaEnsured = true;
8209
+ return;
8210
+ }
8211
+ const where = [{ field: "namespace", op: "eq", value: this.namespace }];
8212
+ if (!await this.db.internal.findOne("__datafn_meta", where)) {
8213
+ try {
8214
+ await this.db.internal.create("__datafn_meta", {
8215
+ id: `meta:${this.namespace}`,
8216
+ namespace: this.namespace,
8217
+ next_server_seq: 1
8218
+ });
8219
+ } catch (error) {
8220
+ if (!await this.db.internal.findOne("__datafn_meta", where)) {
8221
+ throw error;
8222
+ }
8223
+ }
8224
+ }
8225
+ prepared.add(this.namespace);
8226
+ this.namespaceMetaEnsured = true;
8182
8227
  }
8183
8228
  /**
8184
8229
  * REL-011: Create a new ChangeTrackingService with a different db adapter.
@@ -8194,7 +8239,8 @@ var ChangeTrackingService = class _ChangeTrackingService {
8194
8239
  emitChanges ? this.onChange : void 0,
8195
8240
  this.logger,
8196
8241
  this.metaEnsured,
8197
- this.changesEnsured
8242
+ this.changesEnsured,
8243
+ true
8198
8244
  );
8199
8245
  }
8200
8246
  /**
@@ -20385,142 +20431,6 @@ function bytesToBase64Url(bytes) {
20385
20431
  return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
20386
20432
  }
20387
20433
 
20388
- // src/placement-policy.ts
20389
- var CONTINENT_CENTERS = {
20390
- AF: [1.65, 17.68],
20391
- AN: [-82.86, 135],
20392
- AS: [34.05, 100.62],
20393
- EU: [54.53, 15.26],
20394
- NA: [54.53, -105.26],
20395
- OC: [-22.74, 140.02],
20396
- SA: [-14.24, -51.93]
20397
- };
20398
- function finiteCoordinate(value, minimum, maximum) {
20399
- return value !== void 0 && Number.isFinite(value) && value >= minimum && value <= maximum;
20400
- }
20401
- function normalizedCandidates(input) {
20402
- const context = {
20403
- location: input.location ?? null,
20404
- preferredRegionId: normalizedPreferredRegionId(input.preferredRegionId)
20405
- };
20406
- const seen = /* @__PURE__ */ new Set();
20407
- const candidates = input.candidates.map((candidate) => {
20408
- const regionId = candidate.regionId.trim();
20409
- if (!regionId) throw new Error("DATAFN_PLACEMENT_REGION_ID_REQUIRED");
20410
- if (seen.has(regionId)) {
20411
- throw new Error(`DATAFN_PLACEMENT_REGION_DUPLICATE: ${regionId}`);
20412
- }
20413
- seen.add(regionId);
20414
- return regionId === candidate.regionId ? candidate : { ...candidate, regionId };
20415
- });
20416
- return candidates.filter(
20417
- (candidate) => (input.constraints ?? []).every(
20418
- (constraint) => constraint(candidate, context)
20419
- )
20420
- );
20421
- }
20422
- function normalizedPreferredRegionId(preferredRegionId) {
20423
- return preferredRegionId?.trim() || null;
20424
- }
20425
- function compareRegionIds(left, right) {
20426
- return left < right ? -1 : left > right ? 1 : 0;
20427
- }
20428
- function sourceCoordinates(location) {
20429
- if (!location) return null;
20430
- if (finiteCoordinate(location.latitude, -90, 90) && finiteCoordinate(location.longitude, -180, 180)) {
20431
- return {
20432
- coordinates: [location.latitude, location.longitude],
20433
- source: "coordinates"
20434
- };
20435
- }
20436
- const continent = location.continent?.toUpperCase();
20437
- const coordinates = continent ? CONTINENT_CENTERS[continent] : void 0;
20438
- return coordinates ? { coordinates, source: "continent" } : null;
20439
- }
20440
- function radians(degrees) {
20441
- return degrees * Math.PI / 180;
20442
- }
20443
- function distanceKilometers(source, target) {
20444
- const sourceLatitude = radians(source[0]);
20445
- const targetLatitude = radians(target[0]);
20446
- const latitudeDelta = radians(target[0] - source[0]);
20447
- const longitudeDelta = radians(target[1] - source[1]);
20448
- const haversine = Math.sin(latitudeDelta / 2) ** 2 + Math.cos(sourceLatitude) * Math.cos(targetLatitude) * Math.sin(longitudeDelta / 2) ** 2;
20449
- const clampedHaversine = Math.min(1, Math.max(0, haversine));
20450
- return 6371 * 2 * Math.atan2(Math.sqrt(clampedHaversine), Math.sqrt(1 - clampedHaversine));
20451
- }
20452
- function rankDatafnPlacementRegions(input) {
20453
- const candidates = normalizedCandidates(input);
20454
- const source = sourceCoordinates(input.location ?? null);
20455
- if (!source) return [];
20456
- return candidates.flatMap((candidate) => {
20457
- const { latitude, longitude } = candidate;
20458
- return finiteCoordinate(latitude, -90, 90) && finiteCoordinate(longitude, -180, 180) ? [
20459
- {
20460
- regionId: candidate.regionId,
20461
- source: source.source,
20462
- distanceKilometers: distanceKilometers(source.coordinates, [
20463
- latitude,
20464
- longitude
20465
- ])
20466
- }
20467
- ] : [];
20468
- }).sort(
20469
- (left, right) => (left.distanceKilometers ?? 0) - (right.distanceKilometers ?? 0) || compareRegionIds(left.regionId, right.regionId)
20470
- );
20471
- }
20472
- function stableIndex(key, length) {
20473
- let hash = 2166136261;
20474
- for (const byte of new TextEncoder().encode(key)) {
20475
- hash ^= byte;
20476
- hash = Math.imul(hash, 16777619) >>> 0;
20477
- }
20478
- return hash % length;
20479
- }
20480
- function selectDatafnPlacementRegion(input) {
20481
- const candidates = normalizedCandidates(input);
20482
- const preferredRegionId = normalizedPreferredRegionId(
20483
- input.preferredRegionId
20484
- );
20485
- if (preferredRegionId && candidates.some((candidate) => candidate.regionId === preferredRegionId)) {
20486
- return { regionId: preferredRegionId, source: "preferred" };
20487
- }
20488
- const ranked = rankDatafnPlacementRegions({
20489
- candidates,
20490
- location: input.location ?? null
20491
- });
20492
- const nearest = ranked[0];
20493
- if (nearest) return nearest;
20494
- if (input.stableKey !== void 0 && candidates.length > 0) {
20495
- const stableCandidates = [...candidates].sort(
20496
- (left, right) => compareRegionIds(left.regionId, right.regionId)
20497
- );
20498
- const selected = stableCandidates[stableIndex(input.stableKey, stableCandidates.length)];
20499
- if (selected) {
20500
- return { regionId: selected.regionId, source: "stable-fallback" };
20501
- }
20502
- }
20503
- return null;
20504
- }
20505
- function coordinate(value, minimum, maximum) {
20506
- const parsed = typeof value === "number" ? value : Number(value);
20507
- return Number.isFinite(parsed) && parsed >= minimum && parsed <= maximum ? parsed : void 0;
20508
- }
20509
- function readDatafnCloudflarePlacementLocation(request) {
20510
- const cf = request.cf;
20511
- if (!cf) return null;
20512
- const latitude = coordinate(cf.latitude, -90, 90);
20513
- const longitude = coordinate(cf.longitude, -180, 180);
20514
- const continent = typeof cf.continent === "string" && /^[A-Za-z]{2}$/u.test(cf.continent) ? cf.continent.toUpperCase() : void 0;
20515
- if (latitude === void 0 && longitude === void 0 && !continent)
20516
- return null;
20517
- return {
20518
- ...latitude === void 0 ? {} : { latitude },
20519
- ...longitude === void 0 ? {} : { longitude },
20520
- ...continent ? { continent } : {}
20521
- };
20522
- }
20523
-
20524
20434
  exports.AtomicSequenceStore = AtomicSequenceStore;
20525
20435
  exports.ChainedSequenceStore = ChainedSequenceStore;
20526
20436
  exports.DATAFN_MULTI_REGION_CAPABILITY = DATAFN_MULTI_REGION_CAPABILITY;
@@ -20543,11 +20453,8 @@ exports.createSequenceStore = createSequenceStore;
20543
20453
  exports.datafn = datafn;
20544
20454
  exports.datafnMultiRegionPlugin = datafnMultiRegionPlugin;
20545
20455
  exports.migrateDatafnNamespace = migrateDatafnNamespace;
20546
- exports.rankDatafnPlacementRegions = rankDatafnPlacementRegions;
20547
- exports.readDatafnCloudflarePlacementLocation = readDatafnCloudflarePlacementLocation;
20548
20456
  exports.readDatafnPublicLinkToken = readDatafnPublicLinkToken;
20549
20457
  exports.resolveDatafnPublicLink = resolveDatafnPublicLink;
20550
- exports.selectDatafnPlacementRegion = selectDatafnPlacementRegion;
20551
20458
  exports.validateDatafnPlacement = validateDatafnPlacement;
20552
20459
  exports.validateDatafnRoutingBodyLimit = validateDatafnRoutingBodyLimit;
20553
20460
  exports.withDatafnPublicLinksSchema = withDatafnPublicLinksSchema;