akanjs 3.0.0-beta.16 → 3.0.0-beta.18
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/base/base.ts +1 -1
- package/client/csrTypes.ts +1 -31
- package/client/frameConfig.ts +2 -2
- package/client/route/RootLayoutDefinition.ts +0 -6
- package/client/route/RouteDefinition.ts +1 -13
- package/common/CodeTranscript.ts +12 -0
- package/common/codeAgentProfile.ts +54 -0
- package/common/codeAgentWire.ts +31 -0
- package/common/index.ts +5 -0
- package/common/routeConvention.ts +0 -3
- package/constant/constantRegistry.ts +8 -11
- package/document/dataLoader.ts +48 -15
- package/document/loaderInfo.ts +28 -7
- package/fetch/client/fetchClient.ts +14 -12
- package/fetch/client/httpClient.ts +1 -1
- package/local/apps/serverLifecycle/serverLifecycle-local.db-shm +0 -0
- package/local/apps/serverLifecycle/serverLifecycle-local_solid.db-shm +0 -0
- package/package.json +1 -1
- package/server/akanServer.ts +3 -1
- package/server/console.ts +9 -9
- package/server/decorators.ts +3 -64
- package/server/devtools/depsSerializer.ts +1 -4
- package/server/di/diLifecycle.ts +1 -3
- package/server/head.tsx +60 -0
- package/server/imageOptimizer.ts +3 -1
- package/server/resolver/database.resolver.ts +29 -26
- package/server/routeElementComposer.tsx +3 -3
- package/server/routeTreeBuilder.ts +1 -24
- package/server/rscWorker.tsx +10 -21
- package/server/webRouter.ts +12 -8
- package/service/injectInfo.ts +86 -72
- package/service/predefinedAdaptor/cache.adaptor.ts +42 -8
- package/service/predefinedAdaptor/storage.adaptor.ts +6 -6
- package/signal/endpointCache.ts +75 -0
- package/signal/guard.ts +4 -3
- package/signal/middleware.ts +0 -77
- package/signal/signalContext.ts +4 -14
- package/signal/types.ts +4 -5
- package/types/client/csrTypes.d.ts +1 -31
- package/types/client/route/RootLayoutDefinition.d.ts +0 -1
- package/types/client/route/RouteDefinition.d.ts +1 -3
- package/types/common/CodeTranscript.d.ts +3 -1
- package/types/common/codeAgentProfile.d.ts +54 -0
- package/types/common/codeAgentWire.d.ts +28 -0
- package/types/common/index.d.ts +2 -2
- package/types/constant/constantRegistry.d.ts +2 -2
- package/types/document/dataLoader.d.ts +6 -1
- package/types/document/loaderInfo.d.ts +9 -4
- package/types/server/console.d.ts +1 -1
- package/types/server/decorators.d.ts +1 -8
- package/types/server/head.d.ts +10 -0
- package/types/server/routeElementComposer.d.ts +1 -1
- package/types/service/injectInfo.d.ts +17 -14
- package/types/service/predefinedAdaptor/cache.adaptor.d.ts +1 -0
- package/types/service/predefinedAdaptor/storage.adaptor.d.ts +1 -2
- package/types/signal/endpointCache.d.ts +19 -0
- package/types/signal/guard.d.ts +4 -3
- package/types/signal/middleware.d.ts +0 -20
- package/types/signal/signalContext.d.ts +1 -6
- package/types/signal/types.d.ts +4 -5
- package/types/ui/Agent/Menu.d.ts +2 -2
- package/types/ui/Button.d.ts +1 -1
- package/types/ui/CsrImage.d.ts +2 -1
- package/types/ui/Data/Item.d.ts +1 -1
- package/types/ui/Link/CsrLink.d.ts +1 -1
- package/types/ui/Link/types.d.ts +2 -0
- package/types/ui/System/CSR.d.ts +2 -2
- package/types/ui/System/Client.d.ts +2 -3
- package/types/ui/System/Common.d.ts +0 -2
- package/types/ui/System/SSR.d.ts +2 -2
- package/types/ui/recipe/inputRecipe.d.ts +1 -1
- package/ui/Agent/Menu.tsx +2 -2
- package/ui/Button.tsx +1 -1
- package/ui/Constant/Doc.tsx +121 -77
- package/ui/Constant/Graph.tsx +11 -3
- package/ui/CsrImage.tsx +3 -2
- package/ui/Data/Item.tsx +1 -1
- package/ui/Field/Choice.tsx +1 -1
- package/ui/Field/Collection.tsx +4 -3
- package/ui/Image.tsx +1 -0
- package/ui/Link/CsrLink.tsx +5 -1
- package/ui/Link/types.ts +2 -0
- package/ui/System/CSR.tsx +1 -9
- package/ui/System/Client.tsx +2 -4
- package/ui/System/Common.tsx +0 -2
- package/ui/System/SSR.tsx +1 -9
- package/ui/recipe/inputRecipe.ts +1 -1
- package/webkit/bootCsr.tsx +0 -12
- package/webkit/useCamera.tsx +4 -3
- package/webkit/useCsrValues.ts +3 -3
- package/webkit/useFetch.ts +6 -7
- package/server/metadata.tsx +0 -198
- package/types/server/metadata.d.ts +0 -22
- package/types/ui/System/Gtag.d.ts +0 -4
- package/ui/System/Gtag.tsx +0 -69
package/service/injectInfo.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type BackendEnv, type Cls, INJECT_META, PrimitiveRegistry } from "akanjs/base";
|
|
1
|
+
import { type BackendEnv, type Cls, dayjs, INJECT_META, PrimitiveRegistry } from "akanjs/base";
|
|
2
2
|
import {
|
|
3
3
|
type ConstantFieldTypeInput,
|
|
4
4
|
ConstantRegistry,
|
|
@@ -30,7 +30,7 @@ interface InjectBuilderOptions<ReturnType> {
|
|
|
30
30
|
local?: boolean;
|
|
31
31
|
default?: unknown;
|
|
32
32
|
isMap?: boolean;
|
|
33
|
-
|
|
33
|
+
ttl?: number;
|
|
34
34
|
parentRefName: string;
|
|
35
35
|
}
|
|
36
36
|
|
|
@@ -104,7 +104,8 @@ export class InjectInfo<
|
|
|
104
104
|
readonly adaptor?: AdaptorCls;
|
|
105
105
|
readonly default?: unknown;
|
|
106
106
|
readonly isMap?: boolean;
|
|
107
|
-
|
|
107
|
+
/** How long a `memory` value lives by default, in milliseconds — a `set` that names its own `expireAt` wins. */
|
|
108
|
+
readonly ttl?: number;
|
|
108
109
|
readonly parentRefName: string;
|
|
109
110
|
constructor(type: Type, options: InjectBuilderOptions<ReturnType>) {
|
|
110
111
|
this.type = type;
|
|
@@ -116,7 +117,7 @@ export class InjectInfo<
|
|
|
116
117
|
this.set = options.set;
|
|
117
118
|
this.default = options.default;
|
|
118
119
|
this.isMap = options.isMap ?? false;
|
|
119
|
-
this.
|
|
120
|
+
this.ttl = options.ttl;
|
|
120
121
|
this.parentRefName = options.parentRefName;
|
|
121
122
|
}
|
|
122
123
|
static async resolveInjection(
|
|
@@ -261,80 +262,78 @@ export class InjectInfo<
|
|
|
261
262
|
) {
|
|
262
263
|
if (injectInfo.local) {
|
|
263
264
|
Object.defineProperty(instance, propKey, {
|
|
264
|
-
value: injectInfo.default ?? null,
|
|
265
|
+
value: injectInfo.isMap ? new Map() : (injectInfo.default ?? null),
|
|
265
266
|
writable: true,
|
|
266
267
|
enumerable: true,
|
|
267
268
|
});
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
};
|
|
276
|
-
|
|
277
|
-
const setValue = setter(value);
|
|
278
|
-
await cacheAdaptor.hset(topic, propKey, key, setValue, option ?? injectInfo.cacheOption);
|
|
279
|
-
};
|
|
280
|
-
Object.defineProperty(instance, propKey, {
|
|
281
|
-
value: {
|
|
282
|
-
get,
|
|
283
|
-
set,
|
|
284
|
-
delete: async (key: string) => {
|
|
285
|
-
await cacheAdaptor.hdelete(topic, propKey, key);
|
|
286
|
-
},
|
|
287
|
-
getOrInsert: async (key: string, value: unknown, option?: CacheSetOptions) => {
|
|
288
|
-
const existingValue = await get(key);
|
|
289
|
-
if (existingValue !== undefined) return existingValue;
|
|
290
|
-
await set(key, value, option);
|
|
291
|
-
return value;
|
|
292
|
-
},
|
|
293
|
-
getOrInsertComputed: async (
|
|
294
|
-
key: string,
|
|
295
|
-
compute: (key: string) => unknown | Promise<unknown>,
|
|
296
|
-
option?: CacheSetOptions,
|
|
297
|
-
) => {
|
|
298
|
-
const existingValue = await get(key);
|
|
299
|
-
if (existingValue !== undefined) return existingValue;
|
|
300
|
-
const value = await compute(key);
|
|
301
|
-
await set(key, value, option);
|
|
302
|
-
return value;
|
|
303
|
-
},
|
|
304
|
-
keys: async () => await cacheAdaptor.hkeys(topic, propKey),
|
|
305
|
-
entries: async () => {
|
|
306
|
-
const entries = await cacheAdaptor.hentries(topic, propKey);
|
|
307
|
-
return entries.map(([key, value]) => [key, getter(value)]);
|
|
308
|
-
},
|
|
309
|
-
forEach: async (callback: (value: unknown, key: string) => void | Promise<void>) => {
|
|
310
|
-
for (const [key, value] of await cacheAdaptor.hentries(topic, propKey)) await callback(getter(value), key);
|
|
311
|
-
},
|
|
312
|
-
clear: async () => {
|
|
313
|
-
await cacheAdaptor.hclear(topic, propKey);
|
|
314
|
-
},
|
|
315
|
-
},
|
|
316
|
-
});
|
|
317
|
-
} else {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const topic = `akan:memory:${injectInfo.parentRefName}`;
|
|
273
|
+
const getter = injectInfo.get as unknown as (value: unknown) => unknown;
|
|
274
|
+
const setter = injectInfo.set as unknown as (value: unknown) => string | number | Buffer;
|
|
275
|
+
const optionOf = (option?: CacheSetOptions): CacheSetOptions | undefined =>
|
|
276
|
+
option ?? (injectInfo.ttl ? { expireAt: dayjs().add(injectInfo.ttl, "millisecond") } : undefined);
|
|
277
|
+
if (!injectInfo.isMap) {
|
|
318
278
|
Object.defineProperty(instance, propKey, {
|
|
319
279
|
value: {
|
|
320
|
-
get: async () =>
|
|
321
|
-
const getter = injectInfo.get as unknown as (value: unknown) => unknown;
|
|
322
|
-
const value = await cacheAdaptor.get("akan:memory", propKey);
|
|
323
|
-
return value === null ? value : getter(value);
|
|
324
|
-
},
|
|
280
|
+
get: async () => getter((await cacheAdaptor.get(topic, propKey)) ?? undefined),
|
|
325
281
|
set: async (value: unknown, option?: CacheSetOptions) => {
|
|
326
|
-
|
|
327
|
-
const setValue = setter(value);
|
|
328
|
-
await cacheAdaptor.set("akan:memory", propKey, setValue, option ?? injectInfo.cacheOption);
|
|
282
|
+
await cacheAdaptor.set(topic, propKey, setter(value), optionOf(option));
|
|
329
283
|
},
|
|
330
284
|
delete: async () => {
|
|
331
|
-
await cacheAdaptor.delete(
|
|
285
|
+
await cacheAdaptor.delete(topic, propKey);
|
|
332
286
|
},
|
|
333
287
|
},
|
|
334
288
|
writable: false,
|
|
335
289
|
enumerable: true,
|
|
336
290
|
});
|
|
291
|
+
return;
|
|
337
292
|
}
|
|
293
|
+
const get = async (key: string) => {
|
|
294
|
+
const value = await cacheAdaptor.hget(topic, propKey, key);
|
|
295
|
+
return value === undefined || value === null ? undefined : getter(value);
|
|
296
|
+
};
|
|
297
|
+
const set = async (key: string, value: unknown, option?: CacheSetOptions) => {
|
|
298
|
+
await cacheAdaptor.hset(topic, propKey, key, setter(value), optionOf(option));
|
|
299
|
+
};
|
|
300
|
+
Object.defineProperty(instance, propKey, {
|
|
301
|
+
value: {
|
|
302
|
+
get,
|
|
303
|
+
set,
|
|
304
|
+
delete: async (key: string) => {
|
|
305
|
+
await cacheAdaptor.hdelete(topic, propKey, key);
|
|
306
|
+
},
|
|
307
|
+
getOrInsert: async (key: string, value: unknown, option?: CacheSetOptions) => {
|
|
308
|
+
const existingValue = await get(key);
|
|
309
|
+
if (existingValue !== undefined) return existingValue;
|
|
310
|
+
await set(key, value, option);
|
|
311
|
+
return value;
|
|
312
|
+
},
|
|
313
|
+
getOrInsertComputed: async (
|
|
314
|
+
key: string,
|
|
315
|
+
compute: (key: string) => unknown | Promise<unknown>,
|
|
316
|
+
option?: CacheSetOptions,
|
|
317
|
+
) => {
|
|
318
|
+
const existingValue = await get(key);
|
|
319
|
+
if (existingValue !== undefined) return existingValue;
|
|
320
|
+
const value = await compute(key);
|
|
321
|
+
await set(key, value, option);
|
|
322
|
+
return value;
|
|
323
|
+
},
|
|
324
|
+
keys: async () => await cacheAdaptor.hkeys(topic, propKey),
|
|
325
|
+
entries: async () => {
|
|
326
|
+
const entries = await cacheAdaptor.hentries(topic, propKey);
|
|
327
|
+
return entries.map(([key, value]) => [key, getter(value)]);
|
|
328
|
+
},
|
|
329
|
+
forEach: async (callback: (value: unknown, key: string) => void | Promise<void>) => {
|
|
330
|
+
for (const [key, value] of await cacheAdaptor.hentries(topic, propKey)) await callback(getter(value), key);
|
|
331
|
+
},
|
|
332
|
+
clear: async () => {
|
|
333
|
+
await cacheAdaptor.hclear(topic, propKey);
|
|
334
|
+
},
|
|
335
|
+
},
|
|
336
|
+
});
|
|
338
337
|
}
|
|
339
338
|
}
|
|
340
339
|
|
|
@@ -370,7 +369,9 @@ export const injectionBuilder = (parentRefName: string) => ({
|
|
|
370
369
|
ValueRef extends ConstantFieldTypeInput = PlainTypeToFieldType<ExplicitType>,
|
|
371
370
|
MapValue = never,
|
|
372
371
|
DefaultValue extends GetFieldValue<ValueRef, ExplicitType> = never,
|
|
373
|
-
GetFn extends (
|
|
372
|
+
GetFn extends (
|
|
373
|
+
value: MapConstructor extends ValueRef ? FieldToValue<MapValue> : GetFieldValue<ValueRef, ExplicitType>,
|
|
374
|
+
) => unknown = never,
|
|
374
375
|
Local extends boolean = false,
|
|
375
376
|
>(
|
|
376
377
|
modelRef: ValueRef,
|
|
@@ -378,9 +379,13 @@ export const injectionBuilder = (parentRefName: string) => ({
|
|
|
378
379
|
local?: Local;
|
|
379
380
|
default?: DefaultValue;
|
|
380
381
|
of?: MapValue;
|
|
381
|
-
expireAt
|
|
382
|
+
/** Milliseconds each write lives unless the `set` call names its own `expireAt`. */
|
|
383
|
+
ttl?: number;
|
|
384
|
+
/** Turns the stored value — a Map's entry value — into what the code reads; `set` is its inverse. */
|
|
382
385
|
get?: GetFn;
|
|
383
|
-
set?: (
|
|
386
|
+
set?: (
|
|
387
|
+
value: ReturnType<GetFn>,
|
|
388
|
+
) => MapConstructor extends ValueRef ? FieldToValue<MapValue> : GetFieldValue<ValueRef, ExplicitType>;
|
|
384
389
|
} = {},
|
|
385
390
|
) => {
|
|
386
391
|
if (opts.local && (!!opts.get || !!opts.set))
|
|
@@ -392,8 +397,10 @@ export const injectionBuilder = (parentRefName: string) => ({
|
|
|
392
397
|
const valueRef = (isMap ? opts.of : modelRef) as Cls;
|
|
393
398
|
|
|
394
399
|
const isStructured = Array.isArray(valueRef) || !PrimitiveRegistry.has(valueRef);
|
|
395
|
-
|
|
396
|
-
|
|
400
|
+
const read = opts.get as ((value: unknown) => unknown) | undefined;
|
|
401
|
+
const write = opts.set as ((value: unknown) => unknown) | undefined;
|
|
402
|
+
type FieldValue = [GetFn] extends [never] ? GetFieldValue<ValueRef, ExplicitType, MapValue> : ReturnType<GetFn>;
|
|
403
|
+
type MapFieldValue = [GetFn] extends [never] ? FieldToValue<MapValue> : ReturnType<GetFn>;
|
|
397
404
|
type IsNullable = DefaultValue extends never ? true : false;
|
|
398
405
|
type UseValue = IsNullable extends true ? FieldValue | null : FieldValue;
|
|
399
406
|
return new InjectInfo<
|
|
@@ -430,16 +437,23 @@ export const injectionBuilder = (parentRefName: string) => ({
|
|
|
430
437
|
get: (serializedValue: never) => {
|
|
431
438
|
const stored = serializedValue as unknown;
|
|
432
439
|
|
|
440
|
+
if (stored === undefined || stored === null) {
|
|
441
|
+
if (opts.default === undefined) return null;
|
|
442
|
+
return read ? read(opts.default) : opts.default;
|
|
443
|
+
}
|
|
444
|
+
|
|
433
445
|
const rawValue = isStructured && typeof stored === "string" ? JSON.parse(stored) : stored;
|
|
434
|
-
|
|
446
|
+
const value = ConstantRegistry.deserialize(valueRef, rawValue as object, true) ?? null;
|
|
447
|
+
return read && value !== null ? read(value) : value;
|
|
435
448
|
},
|
|
436
449
|
set: (value: never) => {
|
|
437
|
-
const
|
|
450
|
+
const plain = write ? write(value) : value;
|
|
451
|
+
const serialized = ConstantRegistry.serialize(valueRef, plain, true) ?? opts.default ?? null;
|
|
438
452
|
return isStructured ? JSON.stringify(serialized) : serialized;
|
|
439
453
|
},
|
|
440
454
|
default: opts.default as unknown,
|
|
441
455
|
isMap,
|
|
442
|
-
|
|
456
|
+
ttl: opts.ttl,
|
|
443
457
|
parentRefName,
|
|
444
458
|
});
|
|
445
459
|
},
|
|
@@ -83,6 +83,21 @@ export class RedisCache
|
|
|
83
83
|
async delete(topic: string, key: string) {
|
|
84
84
|
await this.redis.del(`${topic}:${key}`);
|
|
85
85
|
}
|
|
86
|
+
|
|
87
|
+
static readonly #purgeScript = `
|
|
88
|
+
local expired = redis.call("ZRANGEBYSCORE", KEYS[2], "-inf", ARGV[1], "LIMIT", 0, 500)
|
|
89
|
+
if #expired > 0 then
|
|
90
|
+
redis.call("HDEL", KEYS[1], unpack(expired))
|
|
91
|
+
redis.call("ZREM", KEYS[2], unpack(expired))
|
|
92
|
+
end
|
|
93
|
+
return #expired`;
|
|
94
|
+
static #ttlKeyOf(redisKey: string) {
|
|
95
|
+
return `${redisKey}:__ttl`;
|
|
96
|
+
}
|
|
97
|
+
async #purgeExpired(redisKey: string) {
|
|
98
|
+
const ttlKey = RedisCache.#ttlKeyOf(redisKey);
|
|
99
|
+
while (Number(await this.redis.eval(RedisCache.#purgeScript, 2, redisKey, ttlKey, Date.now())) >= 500);
|
|
100
|
+
}
|
|
86
101
|
async hset(
|
|
87
102
|
topic: string,
|
|
88
103
|
key: string,
|
|
@@ -92,25 +107,44 @@ export class RedisCache
|
|
|
92
107
|
): Promise<void> {
|
|
93
108
|
const expireTime = option?.expireAt?.toDate().getTime();
|
|
94
109
|
const redisKey = `${topic}:${key}`;
|
|
95
|
-
|
|
96
|
-
|
|
110
|
+
const ttlKey = RedisCache.#ttlKeyOf(redisKey);
|
|
111
|
+
const write = this.redis.multi().hset(redisKey, subKey, value);
|
|
112
|
+
if (expireTime) write.zadd(ttlKey, expireTime, subKey);
|
|
113
|
+
else write.zrem(ttlKey, subKey);
|
|
114
|
+
await write.exec();
|
|
115
|
+
await this.#purgeExpired(redisKey);
|
|
97
116
|
}
|
|
98
117
|
async hget<T extends string | number | Buffer>(topic: string, key: string, subKey: string): Promise<T | undefined> {
|
|
99
|
-
const
|
|
100
|
-
|
|
118
|
+
const redisKey = `${topic}:${key}`;
|
|
119
|
+
const replies = await this.redis
|
|
120
|
+
.multi()
|
|
121
|
+
.hget(redisKey, subKey)
|
|
122
|
+
.zscore(RedisCache.#ttlKeyOf(redisKey), subKey)
|
|
123
|
+
.exec();
|
|
124
|
+
const value = replies?.[0]?.[1] as string | null | undefined;
|
|
125
|
+
const expireAt = replies?.[1]?.[1] as string | null | undefined;
|
|
126
|
+
if (value === null || value === undefined) return undefined;
|
|
127
|
+
if (expireAt !== null && expireAt !== undefined && Number(expireAt) <= Date.now()) return undefined;
|
|
128
|
+
return value as T;
|
|
101
129
|
}
|
|
102
130
|
async hdelete(topic: string, key: string, subKey: string): Promise<void> {
|
|
103
|
-
|
|
131
|
+
const redisKey = `${topic}:${key}`;
|
|
132
|
+
await this.redis.multi().hdel(redisKey, subKey).zrem(RedisCache.#ttlKeyOf(redisKey), subKey).exec();
|
|
104
133
|
}
|
|
105
134
|
async hkeys(topic: string, key: string): Promise<string[]> {
|
|
106
|
-
|
|
135
|
+
const redisKey = `${topic}:${key}`;
|
|
136
|
+
await this.#purgeExpired(redisKey);
|
|
137
|
+
return await this.redis.hkeys(redisKey);
|
|
107
138
|
}
|
|
108
139
|
async hentries<T extends string | number | Buffer>(topic: string, key: string): Promise<[string, T][]> {
|
|
109
|
-
const
|
|
140
|
+
const redisKey = `${topic}:${key}`;
|
|
141
|
+
await this.#purgeExpired(redisKey);
|
|
142
|
+
const values = await this.redis.hgetall(redisKey);
|
|
110
143
|
return Object.entries(values) as [string, T][];
|
|
111
144
|
}
|
|
112
145
|
async hclear(topic: string, key: string): Promise<void> {
|
|
113
|
-
|
|
146
|
+
const redisKey = `${topic}:${key}`;
|
|
147
|
+
await this.redis.del(redisKey, RedisCache.#ttlKeyOf(redisKey));
|
|
114
148
|
}
|
|
115
149
|
getClient(): Redis {
|
|
116
150
|
return this.redis;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { renameSync } from "node:fs";
|
|
2
|
-
import {
|
|
2
|
+
import { getApiPrefix, getEnv } from "akanjs/base";
|
|
3
3
|
import { adapt } from "../adapt";
|
|
4
4
|
|
|
5
5
|
export interface DownloadRequest {
|
|
@@ -52,19 +52,19 @@ export interface StorageAdaptor {
|
|
|
52
52
|
deleteDataByPath(path: string): Promise<boolean>;
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
-
export interface BlobStorageOptions
|
|
55
|
+
export interface BlobStorageOptions {
|
|
56
56
|
blobStorage?: { baseDir?: string; privateBaseDir?: string; urlPrefix?: string };
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
export class BlobStorage
|
|
60
60
|
extends adapt("blobStorage", ({ env }) => ({
|
|
61
61
|
root: env(
|
|
62
|
-
({
|
|
63
|
-
`${process.env.AKAN_WORKSPACE_ROOT ?? "."}/${blobStorage.baseDir ?? "local"}/${appName}/backend`,
|
|
62
|
+
({ blobStorage = { baseDir: "local" } }: BlobStorageOptions) =>
|
|
63
|
+
`${process.env.AKAN_WORKSPACE_ROOT ?? "."}/${blobStorage.baseDir ?? "local"}/${getEnv().appName}/backend`,
|
|
64
64
|
),
|
|
65
65
|
privateRoot: env(
|
|
66
|
-
({
|
|
67
|
-
`${process.env.AKAN_WORKSPACE_ROOT ?? "."}/${blobStorage.privateBaseDir ?? "local"}/${appName}/server-private`,
|
|
66
|
+
({ blobStorage = { privateBaseDir: "local" } }: BlobStorageOptions) =>
|
|
67
|
+
`${process.env.AKAN_WORKSPACE_ROOT ?? "."}/${blobStorage.privateBaseDir ?? "local"}/${getEnv().appName}/server-private`,
|
|
68
68
|
),
|
|
69
69
|
|
|
70
70
|
urlPrefix: env(
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { type CacheAdaptor, CacheAdaptorRole } from "akanjs/service";
|
|
2
|
+
import dayjs from "dayjs";
|
|
3
|
+
import type { SignalContext } from "./signalContext";
|
|
4
|
+
import { traceCache } from "./trace";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Serves an endpoint's own answer back for as long as its declared `cache` allows, and stands aside for every
|
|
8
|
+
* endpoint that declared none — every call passes through here, so a TTL of its own would put a stale window on
|
|
9
|
+
* every call in the app.
|
|
10
|
+
*
|
|
11
|
+
* It runs inside the call, after the guards and the internal arguments, never as a middleware: a middleware sits
|
|
12
|
+
* ahead of the ones a lib registers (the account resolution among them), so a hit served there was judged by
|
|
13
|
+
* guards that could not yet see who was asking. Here a hit reaches only a caller the guards already admitted, and
|
|
14
|
+
* it stays inside the `timeout` deadline, so a cache backend that hangs is bounded like the handler it stands in for.
|
|
15
|
+
*
|
|
16
|
+
* A cached answer is **shared**, which is why only a `query` taking no internal argument can carry one: internal
|
|
17
|
+
* arguments are how a call learns who is asking (`.with(Self)`), so an endpoint that has them answers per caller
|
|
18
|
+
* and one entry would be one caller's answer handed to the next.
|
|
19
|
+
*/
|
|
20
|
+
export class EndpointCache {
|
|
21
|
+
static #topic = "cache";
|
|
22
|
+
static #refused = new Set<string>();
|
|
23
|
+
|
|
24
|
+
static async through(context: SignalContext, run: () => Promise<unknown>) {
|
|
25
|
+
const ttl = context.endpointInfo.signalOption.cache;
|
|
26
|
+
if (!ttl || !Number.isFinite(ttl) || ttl <= 0) return await run();
|
|
27
|
+
if (!EndpointCache.#cacheable(context)) return await run();
|
|
28
|
+
const cache = context.getAdaptor(CacheAdaptorRole) as unknown as CacheAdaptor;
|
|
29
|
+
const key = `${context.key}:${JSON.stringify(context.args)}`;
|
|
30
|
+
const cached = await EndpointCache.#read(context, cache, key);
|
|
31
|
+
if (cached !== undefined) {
|
|
32
|
+
traceCache(true);
|
|
33
|
+
return cached;
|
|
34
|
+
}
|
|
35
|
+
traceCache(false);
|
|
36
|
+
const result = await run();
|
|
37
|
+
await EndpointCache.#write(context, cache, key, result, ttl);
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
/** A `cache` declared where a shared answer would be wrong is named once rather than silently ignored. */
|
|
41
|
+
static #cacheable(context: SignalContext) {
|
|
42
|
+
if (context.endpointInfo.type === "query" && context.endpointInfo.internalArgs.length === 0) return true;
|
|
43
|
+
if (EndpointCache.#refused.has(context.key)) return false;
|
|
44
|
+
EndpointCache.#refused.add(context.key);
|
|
45
|
+
const reason =
|
|
46
|
+
context.endpointInfo.type === "query"
|
|
47
|
+
? "it takes an internal argument, so its answer is the caller's and not a shared one"
|
|
48
|
+
: `a ${context.endpointInfo.type} is never cached`;
|
|
49
|
+
context.adaptor.logger.warn(`"${context.key}" declares \`cache\` and cannot take one: ${reason}.`);
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
/** A cache backend that is down must not take the endpoint down with it: the call runs uncached instead. */
|
|
53
|
+
static async #read(context: SignalContext, cache: CacheAdaptor, key: string) {
|
|
54
|
+
try {
|
|
55
|
+
const cached = await cache.get<string>(EndpointCache.#topic, key);
|
|
56
|
+
if (cached == null) return undefined;
|
|
57
|
+
return JSON.parse(cached) as unknown;
|
|
58
|
+
} catch (error) {
|
|
59
|
+
context.adaptor.logger.warn(`Cache read failed for ${context.key}: ${String(error)}`);
|
|
60
|
+
|
|
61
|
+
await cache.delete(EndpointCache.#topic, key).catch(() => undefined);
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
static async #write(context: SignalContext, cache: CacheAdaptor, key: string, result: unknown, ttl: number) {
|
|
66
|
+
const serialized = JSON.stringify(result);
|
|
67
|
+
|
|
68
|
+
if (serialized === undefined) return;
|
|
69
|
+
try {
|
|
70
|
+
await cache.set(EndpointCache.#topic, key, serialized, { expireAt: dayjs().add(ttl, "millisecond") });
|
|
71
|
+
} catch (error) {
|
|
72
|
+
context.adaptor.logger.warn(`Cache write failed for ${context.key}: ${String(error)}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
package/signal/guard.ts
CHANGED
|
@@ -10,9 +10,10 @@ export interface Guard {
|
|
|
10
10
|
* with no arguments — which is what lets a catalogue hide what the caller certainly cannot use. `resource` needs
|
|
11
11
|
* the call's arguments and fails closed without them, so evaluating one early would erase legitimate entries.
|
|
12
12
|
*
|
|
13
|
-
*
|
|
14
|
-
* silently take the `resource` path and list its endpoint to every caller — the whole
|
|
15
|
-
* refused only at call time.
|
|
13
|
+
* `GuardCls` requires it on a hand-written guard class. Exposure is decided by a guard rather than by an opt-in, so
|
|
14
|
+
* an unmarked guard would silently take the `resource` path and list its endpoint to every caller — the whole
|
|
15
|
+
* guarded surface's names, refused only at call time. A class built with `guard(name)` starts as `account`, the
|
|
16
|
+
* side that errs hidden: a subclass reading the call's arguments without overriding it drops out of every listing.
|
|
16
17
|
*/
|
|
17
18
|
export type GuardScope = "account" | "resource";
|
|
18
19
|
|
package/signal/middleware.ts
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import type { BackendEnv, Cls, PromiseOrObject } from "akanjs/base";
|
|
2
2
|
import { Logger } from "akanjs/common";
|
|
3
|
-
import { type CacheAdaptor, CacheAdaptorRole } from "akanjs/service";
|
|
4
|
-
import dayjs from "dayjs";
|
|
5
3
|
import { Exception } from "./exception";
|
|
6
4
|
import type { SignalContext } from "./signalContext";
|
|
7
|
-
import { traceCache } from "./trace";
|
|
8
5
|
|
|
9
6
|
export interface Middleware<Env extends BackendEnv = BackendEnv> {
|
|
10
7
|
use(env: Env): PromiseOrObject<(context: SignalContext, next: () => Promise<unknown>) => PromiseOrObject<unknown>>;
|
|
@@ -47,80 +44,6 @@ export class Logging extends middleware("logging") {
|
|
|
47
44
|
}
|
|
48
45
|
}
|
|
49
46
|
|
|
50
|
-
/**
|
|
51
|
-
* Serves an endpoint's own answer back for as long as its declared `cache` allows, and stands aside for every
|
|
52
|
-
* endpoint that declared none — this is registered by default, so a TTL of its own would put a stale window on
|
|
53
|
-
* every call in the app.
|
|
54
|
-
*
|
|
55
|
-
* A cached answer is **shared**, which is why only a `query` taking no internal argument can carry one: internal
|
|
56
|
-
* arguments are how a call learns who is asking (`.with(Self)`), so an endpoint that has them answers per caller
|
|
57
|
-
* and one entry would be one caller's answer handed to the next. Guards are re-run on every hit regardless —
|
|
58
|
-
* shared is not public, and `next()`, which is what runs them, is exactly what a hit skips.
|
|
59
|
-
*/
|
|
60
|
-
export class Cache extends middleware("cache") {
|
|
61
|
-
static #topic = "cache";
|
|
62
|
-
static #refused = new Set<string>();
|
|
63
|
-
|
|
64
|
-
override async use() {
|
|
65
|
-
return async (context: SignalContext, next: () => Promise<unknown>) => {
|
|
66
|
-
const ttl = context.endpointInfo.signalOption.cache;
|
|
67
|
-
if (!ttl || !Number.isFinite(ttl) || ttl <= 0) return await next();
|
|
68
|
-
if (!Cache.#cacheable(context)) return await next();
|
|
69
|
-
const cache = context.getAdaptor(CacheAdaptorRole) as unknown as CacheAdaptor;
|
|
70
|
-
const key = `${context.key}:${JSON.stringify(context.args)}`;
|
|
71
|
-
const cached = await Cache.#read(context, cache, key);
|
|
72
|
-
if (cached !== undefined) {
|
|
73
|
-
await context.checkGuards();
|
|
74
|
-
traceCache(true);
|
|
75
|
-
return cached;
|
|
76
|
-
}
|
|
77
|
-
traceCache(false);
|
|
78
|
-
const result = await next();
|
|
79
|
-
await Cache.#write(context, cache, key, result, ttl);
|
|
80
|
-
return result;
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* The handler's inputs are its declared arguments and its internal arguments, so an endpoint with none of the
|
|
85
|
-
* latter answers the same thing to everyone who may read it — which is the only answer a shared entry can hold.
|
|
86
|
-
* A `cache` declared anywhere else is named once rather than silently ignored.
|
|
87
|
-
*/
|
|
88
|
-
static #cacheable(context: SignalContext) {
|
|
89
|
-
if (context.endpointInfo.type === "query" && context.endpointInfo.internalArgs.length === 0) return true;
|
|
90
|
-
if (Cache.#refused.has(context.key)) return false;
|
|
91
|
-
Cache.#refused.add(context.key);
|
|
92
|
-
const reason =
|
|
93
|
-
context.endpointInfo.type === "query"
|
|
94
|
-
? "it takes an internal argument, so its answer is the caller's and not a shared one"
|
|
95
|
-
: `a ${context.endpointInfo.type} is never cached`;
|
|
96
|
-
context.adaptor.logger.warn(`"${context.key}" declares \`cache\` and cannot take one: ${reason}.`);
|
|
97
|
-
return false;
|
|
98
|
-
}
|
|
99
|
-
/** A cache backend that is down must not take the endpoint down with it: the call runs uncached instead. */
|
|
100
|
-
static async #read(context: SignalContext, cache: CacheAdaptor, key: string) {
|
|
101
|
-
try {
|
|
102
|
-
const cached = await cache.get<string>(Cache.#topic, key);
|
|
103
|
-
if (cached == null) return undefined;
|
|
104
|
-
return JSON.parse(cached) as unknown;
|
|
105
|
-
} catch (error) {
|
|
106
|
-
context.adaptor.logger.warn(`Cache read failed for ${context.key}: ${String(error)}`);
|
|
107
|
-
|
|
108
|
-
await cache.delete(Cache.#topic, key).catch(() => undefined);
|
|
109
|
-
return undefined;
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
static async #write(context: SignalContext, cache: CacheAdaptor, key: string, result: unknown, ttl: number) {
|
|
113
|
-
const serialized = JSON.stringify(result);
|
|
114
|
-
|
|
115
|
-
if (serialized === undefined) return;
|
|
116
|
-
try {
|
|
117
|
-
await cache.set(Cache.#topic, key, serialized, { expireAt: dayjs().add(ttl, "millisecond") });
|
|
118
|
-
} catch (error) {
|
|
119
|
-
context.adaptor.logger.warn(`Cache write failed for ${context.key}: ${String(error)}`);
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
47
|
/**
|
|
125
48
|
* Bounds an endpoint that declared a `timeout`, and nothing else — this is registered by default, so a default
|
|
126
49
|
* of its own would put a deadline on every endpoint in the app that nobody asked for.
|
package/signal/signalContext.ts
CHANGED
|
@@ -19,10 +19,10 @@ import {
|
|
|
19
19
|
import type { Adaptor, AdaptorCls, DatabaseService, InjectRegistry, LiveRegistry } from "akanjs/service";
|
|
20
20
|
import type { Internal, InternalCls, InternalInfo, MiddlewareCls } from ".";
|
|
21
21
|
import { CrossSiteGuard } from "./CrossSiteGuard";
|
|
22
|
+
import { EndpointCache } from "./endpointCache";
|
|
22
23
|
import type { EndpointInfo, EndpointType } from "./endpointInfo";
|
|
23
24
|
import { Exception, isExceptionLike } from "./exception";
|
|
24
25
|
import { type GuardCls, guardOf } from "./guard";
|
|
25
|
-
|
|
26
26
|
import { SignalFailure } from "./SignalFailure";
|
|
27
27
|
import { getCurrentTrace, runTraced, SignalTrace, type TraceOrigin, traceSpan } from "./trace";
|
|
28
28
|
|
|
@@ -154,17 +154,10 @@ export class SignalContext<
|
|
|
154
154
|
throw new Exception.Forbidden(`Access denied by guard: ${GuardCls.name}`);
|
|
155
155
|
}
|
|
156
156
|
}
|
|
157
|
-
/**
|
|
158
|
-
* The endpoint's guards, for a middleware that answers a call without executing it — a cache hit skips
|
|
159
|
-
* `next()`, and `next()` is what would otherwise run them. Side-effect free, like the guards themselves.
|
|
160
|
-
*/
|
|
161
|
-
async checkGuards() {
|
|
162
|
-
await this.#checkGuards();
|
|
163
|
-
}
|
|
164
157
|
/**
|
|
165
158
|
* Re-checks this context's guards outside of a request, for a websocket room that is already
|
|
166
159
|
* subscribed. Only global middlewares run: they carry the account resolution this depends on,
|
|
167
|
-
* while endpoint middlewares
|
|
160
|
+
* while endpoint middlewares would observe a call that never executes.
|
|
168
161
|
*/
|
|
169
162
|
async authorize(): Promise<boolean> {
|
|
170
163
|
try {
|
|
@@ -298,11 +291,8 @@ export class SignalContext<
|
|
|
298
291
|
}),
|
|
299
292
|
);
|
|
300
293
|
}
|
|
301
|
-
|
|
302
|
-
return await traceSpan(
|
|
303
|
-
"handler",
|
|
304
|
-
async () => await this.endpointInfo.execFn?.call(this.adaptor, ...this.args, ...this.internalArgs),
|
|
305
|
-
);
|
|
294
|
+
const handle = async () => await this.endpointInfo.execFn?.call(this.adaptor, ...this.args, ...this.internalArgs);
|
|
295
|
+
return await EndpointCache.through(this, this.trace ? () => traceSpan("handler", handle) : handle);
|
|
306
296
|
};
|
|
307
297
|
const next = this.#withMiddleware(coreExec);
|
|
308
298
|
const result = this.trace ? await traceSpan("execChain", () => next()) : await next();
|
package/signal/types.ts
CHANGED
|
@@ -92,14 +92,13 @@ export interface SignalOption<Response = any, Nullable extends boolean = false,
|
|
|
92
92
|
timeout?: number;
|
|
93
93
|
partial?: _Key[] | readonly _Key[];
|
|
94
94
|
/**
|
|
95
|
-
* How long this endpoint's answer may be reused, in milliseconds. The
|
|
96
|
-
*
|
|
97
|
-
* expires; declared nowhere, nothing is cached.
|
|
95
|
+
* How long this endpoint's answer may be reused, in milliseconds. The call keeps the handler's result under the
|
|
96
|
+
* endpoint's key and its arguments and serves it until it expires; declared nowhere, nothing is cached.
|
|
98
97
|
*
|
|
99
98
|
* **Only a `query` that takes no internal argument may carry one.** Internal arguments are how a call learns
|
|
100
99
|
* who is asking (`.with(Self)`), so an endpoint that has them answers per caller, and one shared entry would be
|
|
101
|
-
* one caller's answer handed to the next; such an endpoint is named in the log and left uncached.
|
|
102
|
-
*
|
|
100
|
+
* one caller's answer handed to the next; such an endpoint is named in the log and left uncached. The lookup
|
|
101
|
+
* runs after the guards, so a hit reaches only a caller they admitted — a shared answer is not a public one.
|
|
103
102
|
*/
|
|
104
103
|
cache?: number;
|
|
105
104
|
guards?: GuardCls[];
|
|
@@ -38,7 +38,7 @@ export interface PageConfig {
|
|
|
38
38
|
ssr?: SsrRenderMode;
|
|
39
39
|
/**
|
|
40
40
|
* Opt in to guarded RSC page suffix commits when the page does not require
|
|
41
|
-
* head
|
|
41
|
+
* head updates and the retained route chain head is invariant for
|
|
42
42
|
* sibling navigations under the same layout.
|
|
43
43
|
*/
|
|
44
44
|
rscPatchHeadSafe?: boolean;
|
|
@@ -106,7 +106,6 @@ export interface AkanHeadSnapshotV1 {
|
|
|
106
106
|
}
|
|
107
107
|
export interface ResolvedHead {
|
|
108
108
|
node: Head | null | undefined;
|
|
109
|
-
hasExplicitLanguageAlternates: boolean;
|
|
110
109
|
headSnapshot?: AkanHeadSnapshotV1;
|
|
111
110
|
}
|
|
112
111
|
export type ResolveHeadResult = Head | ResolvedHead | null | undefined;
|
|
@@ -160,53 +159,24 @@ export interface WebAppManifest {
|
|
|
160
159
|
screenshots?: WebAppManifestIcon[];
|
|
161
160
|
[key: string]: unknown;
|
|
162
161
|
}
|
|
163
|
-
export interface AkanMetadata {
|
|
164
|
-
title?: string;
|
|
165
|
-
description?: string;
|
|
166
|
-
robots?: string;
|
|
167
|
-
openGraph?: {
|
|
168
|
-
title?: string;
|
|
169
|
-
description?: string;
|
|
170
|
-
type?: string;
|
|
171
|
-
url?: string;
|
|
172
|
-
siteName?: string;
|
|
173
|
-
images?: string | string[];
|
|
174
|
-
};
|
|
175
|
-
twitter?: {
|
|
176
|
-
card?: "summary" | "summary_large_image" | "app" | "player" | (string & {});
|
|
177
|
-
title?: string;
|
|
178
|
-
description?: string;
|
|
179
|
-
images?: string | string[];
|
|
180
|
-
};
|
|
181
|
-
alternates?: {
|
|
182
|
-
canonical?: string;
|
|
183
|
-
languages?: Record<string, string>;
|
|
184
|
-
};
|
|
185
|
-
}
|
|
186
|
-
export type GenerateMetadata = (props: PageProps) => PromiseOrObject<AkanMetadata | null | undefined>;
|
|
187
162
|
export interface PageModule {
|
|
188
163
|
default?: PageRender;
|
|
189
164
|
pageConfig?: PageConfig;
|
|
190
165
|
head?: Head;
|
|
191
|
-
metadata?: AkanMetadata;
|
|
192
166
|
generateHead?: GenerateHead;
|
|
193
|
-
generateMetadata?: GenerateMetadata;
|
|
194
167
|
Loading?: PageLoadingRender;
|
|
195
168
|
}
|
|
196
169
|
export interface LayoutModule {
|
|
197
170
|
default?: LayoutRender;
|
|
198
171
|
pageConfig?: PageConfig;
|
|
199
172
|
head?: Head;
|
|
200
|
-
metadata?: AkanMetadata;
|
|
201
173
|
generateHead?: GenerateHead;
|
|
202
|
-
generateMetadata?: GenerateMetadata;
|
|
203
174
|
fonts?: ReactFont[];
|
|
204
175
|
manifest?: WebAppManifest;
|
|
205
176
|
theme?: string;
|
|
206
177
|
reconnect?: boolean;
|
|
207
178
|
wsConnect?: boolean;
|
|
208
179
|
layoutStyle?: "mobile" | "web";
|
|
209
|
-
gaTrackingId?: string;
|
|
210
180
|
Loading?: LayoutLoadingRender;
|
|
211
181
|
NotFound?: LayoutNotFoundRender;
|
|
212
182
|
Error?: LayoutErrorRender;
|