@datafn/server 0.1.0 → 0.1.1

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,6 +37,34 @@ 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
+
40
68
  ---
41
69
 
42
70
  ## Quick Start
package/dist/index.cjs CHANGED
@@ -20385,6 +20385,142 @@ function bytesToBase64Url(bytes) {
20385
20385
  return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
20386
20386
  }
20387
20387
 
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
+
20388
20524
  exports.AtomicSequenceStore = AtomicSequenceStore;
20389
20525
  exports.ChainedSequenceStore = ChainedSequenceStore;
20390
20526
  exports.DATAFN_MULTI_REGION_CAPABILITY = DATAFN_MULTI_REGION_CAPABILITY;
@@ -20407,8 +20543,11 @@ exports.createSequenceStore = createSequenceStore;
20407
20543
  exports.datafn = datafn;
20408
20544
  exports.datafnMultiRegionPlugin = datafnMultiRegionPlugin;
20409
20545
  exports.migrateDatafnNamespace = migrateDatafnNamespace;
20546
+ exports.rankDatafnPlacementRegions = rankDatafnPlacementRegions;
20547
+ exports.readDatafnCloudflarePlacementLocation = readDatafnCloudflarePlacementLocation;
20410
20548
  exports.readDatafnPublicLinkToken = readDatafnPublicLinkToken;
20411
20549
  exports.resolveDatafnPublicLink = resolveDatafnPublicLink;
20550
+ exports.selectDatafnPlacementRegion = selectDatafnPlacementRegion;
20412
20551
  exports.validateDatafnPlacement = validateDatafnPlacement;
20413
20552
  exports.validateDatafnRoutingBodyLimit = validateDatafnRoutingBodyLimit;
20414
20553
  exports.withDatafnPublicLinksSchema = withDatafnPublicLinksSchema;