Merge fix/token-mints into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 95c7310, db7cae8 · Browse files · 2 files·+122 added−43 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+122 added−43 removed
- tests:+62 added−0 removed
- other:+60 added−43 removed
Provenance
- Commit
470b13a- Tree
a83f361- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
95c7310- Parent 2
db7cae8
2 files changed+122 added−43 removed
modified:packages/git/src/upstream/repo-host.ts+60 added-43 removed
12345678910111213456783 unmodified lines121314152526272816171819202122232428 unmodified lines535455566557585960616263646566676869707173747576777872737475768081828384858687888990919293949596979877787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191031041051201211221231241251269 unmodified linesimport { Fetch } from "@repo/artifacts/fetch";import { RepoHost } from "@repo/artifacts/repo-host";import type { RepoName, TokenScope } from "@repo/artifacts/repo-host";import { Cache, Data, DateTime, Duration, Effect, Exit, Layer, Redacted,} from "effect";import { DateTime, Duration, Effect, Layer, Redacted, Ref } from "effect";
import { Exchange, Upstream, UpstreamFailure } from "../upstream.ts";import type { Service } from "../upstream.ts";
3 unmodified linesconst MARGIN = Duration.minutes(1);
const CAPACITY = 1024;
class TokenKey extends Data.Class<{ readonly repo: RepoName; readonly scope: TokenScope;}> {}interface Credentials { readonly authorization: string; readonly remote: string; readonly until: DateTime.Utc;}
const scopeOf = (service: Service): TokenScope => service === "git-receive-pack" ? "write" : "read";
28 unmodified lines }, });};
/** Tokens are cached per (repo, scope) in a cache made when the layer is built: one per isolate. *//** * Tokens are kept per (repo, scope) in a map made when the layer is built: one * per isolate. A token being minted is never shared: on Workers a request that * awaits another request's I/O is cancelled as hung, and a request whose * client leaves is cancelled where it stands, so its mint may never end. Two * requests that miss at once each mint their own. */export const UpstreamRepoHost: Layer.Layer<Upstream, never, RepoHost | Fetch> = Layer.effect( Upstream, Effect.gen(function* () { const host = yield* RepoHost; const client = yield* Fetch; const kept = yield* Ref.make<ReadonlyMap<string, Credentials>>(new Map());
const credentials = yield* Cache.makeWith( ({ repo, scope }: TokenKey) => Effect.gen(function* () { const remote = yield* host.remote(repo); const token = yield* host.mintToken(repo, scope, TOKEN_TTL); const now = yield* DateTime.now; const credentialsOf = (repo: RepoName, scope: TokenScope) => Effect.gen(function* () { const key = `${scope}:${repo}`; const found = (yield* Ref.get(kept)).get(key);
return { authorization: basic(token.secret), lasts: Duration.subtract( DateTime.distance(now, token.expiresAt), MARGIN ), remote, }; }), { capacity: CAPACITY, // A failed mint is not kept, nor a token too short-lived to use. timeToLive: (exit) => Exit.isSuccess(exit) && Duration.isGreaterThan(exit.value.lasts, Duration.zero) ? exit.value.lasts : Duration.zero, } ); if ( found !== undefined && DateTime.isLessThan(yield* DateTime.now, found.until) ) { return found; }
const remote = yield* host.remote(repo); const token = yield* host.mintToken(repo, scope, TOKEN_TTL); const now = yield* DateTime.now;
const fresh: Credentials = { authorization: basic(token.secret), remote, until: DateTime.subtractDuration(token.expiresAt, MARGIN), };
// A token too short-lived to use is not kept. if (DateTime.isLessThan(now, fresh.until)) { yield* Ref.update(kept, (all) => { const next = new Map(all);
next.delete(key); next.set(key, fresh);
for (const oldest of next.keys()) { if (next.size <= CAPACITY) { break; }
next.delete(oldest); }
return next; }); }
return fresh; });
return Upstream.of({ exchange: (repo, exchange) => Effect.gen(function* () { const { authorization, remote } = yield* Cache.get( credentials, new TokenKey({ repo, scope: scopeOf(exchange.service) }) const { authorization, remote } = yield* credentialsOf( repo, scopeOf(exchange.service) );
return yield* client .fetch(requestOf(remote, exchange, authorization))9 unmodified linesmodified:packages/git/test/upstream.test.ts+62 added
5 unmodified lines6 import {7 DateTime,8 Duration,9 Effect,10+ Fiber,11 Layer,12+ Option,13 Redacted,14 Ref,15 Stream,16 } from "effect";205 unmodified lines222 })223 )224 );225 226+ // On Workers a request that awaits another request's I/O is cancelled as hung,227+ // and one whose client left is cancelled where it stands: its mint never ends.228+ it.live(229+ "never has an exchange wait on a token another exchange is minting",230+ () =>231+ Effect.gen(function* () {232+ const mints = yield* Ref.make(0);233+ const requests = yield* Ref.make<readonly Request[]>([]);234+235+ const stalling = Layer.effect(236+ RepoHost,237+ Effect.gen(function* () {238+ const host = yield* RepoHost;239+240+ return RepoHost.of({241+ ...host,242+ mintToken: (name, scope, ttl) =>243+ Effect.flatMap(244+ Ref.getAndUpdate(mints, (count) => count + 1),245+ (count) =>246+ count === 0247+ ? Effect.never248+ : host.mintToken(name, scope, ttl)249+ ),250+ });251+ })252+ ).pipe(Layer.provide(RepoHostMemory));253+254+ const later = yield* Effect.gen(function* () {255+ yield* RepoHost.use((host) => host.create(repo)).pipe(Effect.orDie);256+257+ const upstream = yield* Upstream;258+259+ const abandoned = yield* Effect.forkChild(260+ upstream.exchange(repo, advertise)261+ );262+263+ yield* Effect.yieldNow;264+265+ const answered = yield* Effect.timeoutOption(266+ Effect.as(upstream.exchange(repo, advertise), "answered"),267+ "2 seconds"268+ );269+270+ yield* Fiber.interrupt(abandoned);271+272+ return answered;273+ }).pipe(274+ Effect.provide(275+ UpstreamRepoHost.pipe(276+ Layer.provideMerge(Layer.mergeAll(stalling, recording(requests)))277+ )278+ )279+ );280+281+ expect(later).toStrictEqual(Option.some("answered"));282+ expect(yield* Ref.get(mints)).toBe(2);283+ })284+ );285+286 it.effect("calls a request that got no response an UpstreamFailure", () =>287 Effect.gen(function* () {288 const unreachable = Layer.succeed(289 Fetch,48 unmodified lines