Compare commits

...

47 Commits

Author SHA1 Message Date
IshaVenikar
59329c18f6 Update method to rollback deployment 2025-02-03 19:33:40 +05:30
Shreerang Kale
8553c30b0d Update comment note 2025-02-03 19:04:41 +05:30
IshaVenikar
b409d43e51 Update flow for deleting deployments
All checks were successful
Lint / lint (20.x) (pull_request) Successful in 4m35s
2025-02-03 17:49:06 +05:30
Shreerang Kale
b50efe315b Remove hyperlink from deployer base domains 2025-02-03 17:14:49 +05:30
IshaVenikar
ced815802e Update deployment request config value if not env variables are set 2025-02-03 16:40:03 +05:30
Shreerang Kale
22bb409617 Add check for while accessing project URL
All checks were successful
Lint / lint (20.x) (pull_request) Successful in 4m34s
2025-02-03 15:47:06 +05:30
IshaVenikar
8322f877c0 Fix check for old DNS deployment 2025-02-03 15:40:05 +05:30
Shreerang Kale
fd38127cb5 Update query to get latest DNS record 2025-02-03 13:39:58 +05:30
Shreerang Kale
b6084008b8 Remove unused GQL methods 2025-02-03 13:28:35 +05:30
IshaVenikar
d1e6171874 Send DNS deployment removal request on changing custom domain 2025-02-03 13:26:26 +05:30
Shreerang Kale
ce56a4dc29 Update UI when DNS record is not present 2025-02-03 11:54:16 +05:30
IshaVenikar
c685b7d5b1 Rename method for getting commit deployments by Id
All checks were successful
Lint / lint (20.x) (pull_request) Successful in 4m36s
2025-02-03 11:15:19 +05:30
IshaVenikar
32001b3d5a Set types for fetched registry records 2025-02-03 10:47:45 +05:30
IshaVenikar
6f32ea4da8 Update comments for update deployment data flow 2025-02-03 10:30:26 +05:30
Shreerang Kale
a16b44b43a Rename Latest DNS response type 2025-02-03 10:10:19 +05:30
IshaVenikar
a17386eb68 Update method name to get record by Id
All checks were successful
Lint / lint (20.x) (pull_request) Successful in 4m40s
2025-02-03 09:23:03 +05:30
Shreerang Kale
f318a95641 Fix custom domain not showing up in UI 2025-02-03 09:23:03 +05:30
Shreerang Kale
e9f746cd8b Revert removing order while getting latest DNS data 2025-02-03 09:23:03 +05:30
IshaVenikar
e59c14440c Fix check for setting isCurrent 2025-02-03 09:23:03 +05:30
IshaVenikar
22f8a8c943 Update method to return single DNS record by ID 2025-02-03 09:23:03 +05:30
IshaVenikar
df5062c75f Remove ununsed imports 2025-02-03 09:23:03 +05:30
Shreerang Kale
22e814840e Fix method to get latest DNS data 2025-02-03 09:23:03 +05:30
IshaVenikar
9d27dd568a Update isCurrent status for commit deployments 2025-02-03 09:23:03 +05:30
Shreerang Kale
fc62392c83 Update methods for using stored DNS deployments in UI 2025-02-03 09:23:03 +05:30
IshaVenikar
2ee65b8fd8 Remove ununsed variables 2025-02-03 09:23:03 +05:30
IshaVenikar
d0302d0153 Store domain for DNS deployments after previous deployment is deleted 2025-02-03 09:23:03 +05:30
Shreerang Kale
90e9260eb6 Update UI when IP address is unavailable and project is created via auctions 2025-02-03 09:23:03 +05:30
IshaVenikar
6dcee29487 Update flow for deleting deployments 2025-02-03 09:23:03 +05:30
IshaVenikar
5be10b6b0a Implement functionality to store DNS deployment 2025-02-03 09:23:01 +05:30
Shreerang Kale
6e8af82dc2 Make service provider domains non clickable 2025-02-03 09:18:14 +05:30
Shreerang Kale
1a5ab4d47e Remove showing domain status in overview pannel 2025-02-03 09:18:14 +05:30
Shreerang Kale
6df685831f Populate domainId while creating deployment 2025-02-03 09:18:14 +05:30
IshaVenikar
13892015a5 Store DNS deployment records data in Deployment entity 2025-02-03 09:18:14 +05:30
Shreerang Kale
55500b5914 Display custom domain in project card 2025-02-03 09:18:14 +05:30
Shreerang Kale
a7190ed804 Show custom domain in overview tabs panel 2025-02-03 09:18:14 +05:30
Shreerang Kale
6a79ee5c47 Remove UI elements for domain verification 2025-02-03 09:18:14 +05:30
Shreerang Kale
f2ba931961 Update method to show IP address 2025-02-03 09:18:14 +05:30
IshaVenikar
85b4265fbe Query DNS records by Id 2025-02-03 09:18:14 +05:30
Shreerang Kale
63223a4807 Get DNS records for all completed deployments 2025-02-03 09:18:14 +05:30
Shreerang Kale
9784eb4f4a Fix DNS records data not getting stored in the DB 2025-02-03 09:18:14 +05:30
Shreerang Kale
624f36155a Fix deploy button disabled for deployers with no min payment 2025-02-03 09:18:14 +05:30
IshaVenikar
82c4b71694 Use oldest custom domain in deployment requests 2025-02-03 09:18:14 +05:30
Shreerang Kale
5d9c965f54 Show service provider IP address while creating custom domain 2025-02-03 09:18:14 +05:30
IshaVenikar
56eccb48b3 Add method to fetch DNS data for latest deployment 2025-02-03 09:18:14 +05:30
Shreerang Kale
b5762432e6 Remove redirect domain from edit domain form 2025-02-03 09:18:14 +05:30
Shreerang Kale
4ae4670dca Remove redirect domain creation while adding custom domain 2025-02-03 09:18:14 +05:30
IshaVenikar
c202554002 Store DNS record data for deployments 2025-02-03 09:18:14 +05:30
20 changed files with 782 additions and 385 deletions

View File

@ -17,13 +17,14 @@ import { DatabaseConfig } from './config';
import { User } from './entity/User'; import { User } from './entity/User';
import { Organization } from './entity/Organization'; import { Organization } from './entity/Organization';
import { Project } from './entity/Project'; import { Project } from './entity/Project';
import { Deployment } from './entity/Deployment'; import { Deployment, DeploymentStatus } from './entity/Deployment';
import { ProjectMember } from './entity/ProjectMember'; import { ProjectMember } from './entity/ProjectMember';
import { EnvironmentVariable } from './entity/EnvironmentVariable'; import { EnvironmentVariable } from './entity/EnvironmentVariable';
import { Domain } from './entity/Domain'; import { Domain } from './entity/Domain';
import { getEntities, loadAndSaveData } from './utils'; import { getEntities, loadAndSaveData } from './utils';
import { UserOrganization } from './entity/UserOrganization'; import { UserOrganization } from './entity/UserOrganization';
import { Deployer } from './entity/Deployer'; import { Deployer } from './entity/Deployer';
import { DNSRecordAttributes } from './types';
const ORGANIZATION_DATA_PATH = '../test/fixtures/organizations.json'; const ORGANIZATION_DATA_PATH = '../test/fixtures/organizations.json';
@ -60,7 +61,7 @@ export class Database {
// Hotfix for updating old DB data // Hotfix for updating old DB data
if (organizations[0].slug === 'snowball-tools-1') { if (organizations[0].slug === 'snowball-tools-1') {
const [orgEntity] = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH)); const [orgEntity] = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH));
await this.updateOrganization( await this.updateOrganization(
organizations[0].id, organizations[0].id,
{ {
@ -157,7 +158,7 @@ export class Database {
.leftJoinAndSelect( .leftJoinAndSelect(
'project.deployments', 'project.deployments',
'deployments', 'deployments',
'deployments.isCurrent = true' 'deployments.isCurrent = true AND deployments.isDNS = true'
) )
.leftJoinAndSelect('deployments.createdBy', 'user') .leftJoinAndSelect('deployments.createdBy', 'user')
.leftJoinAndSelect('deployments.domain', 'domain') .leftJoinAndSelect('deployments.domain', 'domain')
@ -202,7 +203,7 @@ export class Database {
.leftJoinAndSelect( .leftJoinAndSelect(
'project.deployments', 'project.deployments',
'deployments', 'deployments',
'deployments.isCurrent = true' 'deployments.isCurrent = true AND deployments.isDNS = true'
) )
.leftJoinAndSelect('deployments.domain', 'domain') .leftJoinAndSelect('deployments.domain', 'domain')
.leftJoin('project.projectMembers', 'projectMembers') .leftJoin('project.projectMembers', 'projectMembers')
@ -250,6 +251,26 @@ export class Database {
}); });
} }
async getCommitDeploymentsByProjectId(projectId: string): Promise<Deployment[]> {
return this.getDeployments({
relations: {
project: true,
domain: true,
createdBy: true,
deployer: true,
},
where: {
project: {
id: projectId
},
isDNS: false
},
order: {
createdAt: 'DESC'
}
});
}
async getDeployment( async getDeployment(
options: FindOneOptions<Deployment> options: FindOneOptions<Deployment>
): Promise<Deployment | null> { ): Promise<Deployment | null> {
@ -602,6 +623,49 @@ export class Database {
return domains; return domains;
} }
async getOldestDomainByProjectId(
projectId: string,
): Promise<Domain | null> {
const domainRepository = this.dataSource.getRepository(Domain);
const domain = await domainRepository.findOne({
where: {
project: {
id: projectId
},
},
order: {
createdAt: 'ASC'
}
});
return domain;
}
async getLatestDNSRecordByProjectId(
projectId: string,
): Promise<DNSRecordAttributes | null> {
const deploymentRepository = this.dataSource.getRepository(Deployment);
const deployment = await deploymentRepository.findOne({
where: {
project: {
id: projectId,
},
status: DeploymentStatus.Ready,
},
order: {
createdAt: 'DESC'
}
});
if (deployment === null) {
throw new Error(`No deployment found for project ${projectId}`);
}
return deployment.dnsRecordData;
}
async addDeployer(data: DeepPartial<Deployer>): Promise<Deployer> { async addDeployer(data: DeepPartial<Deployer>): Promise<Deployer> {
const deployerRepository = this.dataSource.getRepository(Deployer); const deployerRepository = this.dataSource.getRepository(Deployer);
const newDomain = await deployerRepository.save(data); const newDomain = await deployerRepository.save(data);

View File

@ -14,7 +14,7 @@ import { Project } from './Project';
import { Domain } from './Domain'; import { Domain } from './Domain';
import { User } from './User'; import { User } from './User';
import { Deployer } from './Deployer'; import { Deployer } from './Deployer';
import { AppDeploymentRecordAttributes, AppDeploymentRemovalRecordAttributes } from '../types'; import { AppDeploymentRecordAttributes, AppDeploymentRemovalRecordAttributes, DNSRecordAttributes } from '../types';
export enum Environment { export enum Environment {
Production = 'Production', Production = 'Production',
@ -126,6 +126,9 @@ export class Deployment {
@Column('simple-json', { nullable: true }) @Column('simple-json', { nullable: true })
applicationDeploymentRemovalRecordData!: AppDeploymentRemovalRecordAttributes | null; applicationDeploymentRemovalRecordData!: AppDeploymentRemovalRecordAttributes | null;
@Column('simple-json', { nullable: true })
dnsRecordData!: DNSRecordAttributes | null;
@ManyToOne(() => Deployer) @ManyToOne(() => Deployer)
@JoinColumn({ name: 'deployerLrn' }) @JoinColumn({ name: 'deployerLrn' })
deployer!: Deployer; deployer!: Deployer;
@ -138,6 +141,10 @@ export class Deployment {
@Column('boolean', { default: false }) @Column('boolean', { default: false })
isCurrent!: boolean; isCurrent!: boolean;
// TODO: Rename field
@Column('boolean', { default: false })
isDNS!: boolean;
@Column({ @Column({
enum: DeploymentStatus enum: DeploymentStatus
}) })

View File

@ -16,7 +16,7 @@ import {
ApplicationDeploymentRequest, ApplicationDeploymentRequest,
ApplicationDeploymentRemovalRequest ApplicationDeploymentRemovalRequest
} from './entity/Deployment'; } from './entity/Deployment';
import { AppDeploymentRecord, AppDeploymentRemovalRecord, AuctionParams, DeployerRecord } from './types'; import { AppDeploymentRecord, AppDeploymentRemovalRecord, AuctionParams, DeployerRecord, RegistryRecord } from './types';
import { getConfig, getRepoDetails, registryTransactionWithRetry, sleep } from './utils'; import { getConfig, getRepoDetails, registryTransactionWithRetry, sleep } from './utils';
const log = debug('snowball:registry'); const log = debug('snowball:registry');
@ -27,7 +27,7 @@ const APP_DEPLOYMENT_REQUEST_TYPE = 'ApplicationDeploymentRequest';
const APP_DEPLOYMENT_REMOVAL_REQUEST_TYPE = 'ApplicationDeploymentRemovalRequest'; const APP_DEPLOYMENT_REMOVAL_REQUEST_TYPE = 'ApplicationDeploymentRemovalRequest';
const APP_DEPLOYMENT_RECORD_TYPE = 'ApplicationDeploymentRecord'; const APP_DEPLOYMENT_RECORD_TYPE = 'ApplicationDeploymentRecord';
const APP_DEPLOYMENT_REMOVAL_RECORD_TYPE = 'ApplicationDeploymentRemovalRecord'; const APP_DEPLOYMENT_REMOVAL_RECORD_TYPE = 'ApplicationDeploymentRemovalRecord';
const WEBAPP_DEPLOYER_RECORD_TYPE = 'WebappDeployer' const WEBAPP_DEPLOYER_RECORD_TYPE = 'WebappDeployer';
const SLEEP_DURATION = 1000; const SLEEP_DURATION = 1000;
// TODO: Move registry code to registry-sdk/watcher-ts // TODO: Move registry code to registry-sdk/watcher-ts
@ -108,19 +108,7 @@ export class Registry {
...(packageJSON.version && { app_version: packageJSON.version }) ...(packageJSON.version && { app_version: packageJSON.version })
}; };
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees); const result = await this.publishRecord(applicationRecord);
const result = await registryTransactionWithRetry(() =>
this.registry.setRecord(
{
privateKey: this.registryConfig.privateKey,
record: applicationRecord,
bondId: this.registryConfig.bondId
},
this.registryConfig.privateKey,
fee
)
);
log(`Published application record ${result.id}`); log(`Published application record ${result.id}`);
log('Application record data:', applicationRecord); log('Application record data:', applicationRecord);
@ -129,6 +117,8 @@ export class Registry {
const lrn = this.getLrn(repo); const lrn = this.getLrn(repo);
log(`Setting name: ${lrn} for record ID: ${result.id}`); log(`Setting name: ${lrn} for record ID: ${result.id}`);
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees);
await sleep(SLEEP_DURATION); await sleep(SLEEP_DURATION);
await registryTransactionWithRetry(() => await registryTransactionWithRetry(() =>
this.registry.setName( this.registry.setName(
@ -220,17 +210,7 @@ export class Registry {
type: APP_DEPLOYMENT_AUCTION_RECORD_TYPE, type: APP_DEPLOYMENT_AUCTION_RECORD_TYPE,
}; };
const result = await registryTransactionWithRetry(() => const result = await this.publishRecord(applicationDeploymentAuction);
this.registry.setRecord(
{
privateKey: this.registryConfig.privateKey,
record: applicationDeploymentAuction,
bondId: this.registryConfig.bondId
},
this.registryConfig.privateKey,
fee
)
);
log(`Application deployment auction created: ${auctionResult.auction.id}`); log(`Application deployment auction created: ${auctionResult.auction.id}`);
log(`Application deployment auction record published: ${result.id}`); log(`Application deployment auction record published: ${result.id}`);
@ -265,12 +245,15 @@ export class Registry {
throw new Error(`No record found for ${lrn}`); throw new Error(`No record found for ${lrn}`);
} }
const hash = await this.generateConfigHash( let hash;
data.environmentVariables, if (Object.keys(data.environmentVariables).length !== 0) {
data.requesterAddress, hash = await this.generateConfigHash(
data.publicKey, data.environmentVariables,
data.apiUrl, data.requesterAddress,
); data.publicKey,
data.apiUrl,
);
}
// Create record of type ApplicationDeploymentRequest and publish // Create record of type ApplicationDeploymentRequest and publish
const applicationDeploymentRequest = { const applicationDeploymentRequest = {
@ -281,9 +264,7 @@ export class Registry {
dns: data.dns, dns: data.dns,
// https://git.vdb.to/cerc-io/laconic-registry-cli/commit/129019105dfb93bebcea02fde0ed64d0f8e5983b // https://git.vdb.to/cerc-io/laconic-registry-cli/commit/129019105dfb93bebcea02fde0ed64d0f8e5983b
config: JSON.stringify({ config: JSON.stringify(hash ? { ref: hash } : {}),
ref: hash,
}),
meta: JSON.stringify({ meta: JSON.stringify({
note: `Added by Snowball @ ${DateTime.utc().toFormat( note: `Added by Snowball @ ${DateTime.utc().toFormat(
"EEE LLL dd HH:mm:ss 'UTC' yyyy" "EEE LLL dd HH:mm:ss 'UTC' yyyy"
@ -298,19 +279,7 @@ export class Registry {
await sleep(SLEEP_DURATION); await sleep(SLEEP_DURATION);
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees); const result = await this.publishRecord(applicationDeploymentRequest);
const result = await registryTransactionWithRetry(() =>
this.registry.setRecord(
{
privateKey: this.registryConfig.privateKey,
record: applicationDeploymentRequest,
bondId: this.registryConfig.bondId
},
this.registryConfig.privateKey,
fee
)
);
log(`Application deployment request record published: ${result.id}`); log(`Application deployment request record published: ${result.id}`);
log('Application deployment request data:', applicationDeploymentRequest); log('Application deployment request data:', applicationDeploymentRequest);
@ -382,12 +351,11 @@ export class Registry {
true true
); );
// Filter records with ApplicationDeploymentRequestId ID and Deployment specific URL // Filter records with ApplicationDeploymentRequestId ID
return records.filter((record: AppDeploymentRecord) => return records.filter((record: AppDeploymentRecord) =>
deployments.some( deployments.some(
(deployment) => (deployment) =>
deployment.applicationDeploymentRequestId === record.attributes.request && deployment.applicationDeploymentRequestId === record.attributes.request
record.attributes.url.includes(deployment.id)
) )
); );
} }
@ -442,6 +410,18 @@ export class Registry {
); );
} }
/**
* Fetch record by Id
*/
async getRecordById(id: string): Promise<RegistryRecord | null> {
const record = await this.registry.getRecordsByIds([id]);
if (record.length === 0) {
return null;
}
return record[0];
}
async createApplicationDeploymentRemovalRequest(data: { async createApplicationDeploymentRemovalRequest(data: {
deploymentId: string; deploymentId: string;
deployerLrn: string; deployerLrn: string;
@ -460,18 +440,8 @@ export class Registry {
...(data.payment && { payment: data.payment }), ...(data.payment && { payment: data.payment }),
}; };
const fee = parseGasAndFees(this.registryConfig.fee.gas, this.registryConfig.fee.fees); const result = await this.publishRecord(
applicationDeploymentRemovalRequest,
const result = await registryTransactionWithRetry(() =>
this.registry.setRecord(
{
privateKey: this.registryConfig.privateKey,
record: applicationDeploymentRemovalRequest,
bondId: this.registryConfig.bondId
},
this.registryConfig.privateKey,
fee
)
); );
log(`Application deployment removal request record published: ${result.id}`); log(`Application deployment removal request record published: ${result.id}`);
@ -497,6 +467,27 @@ export class Registry {
return completedAuctions; return completedAuctions;
} }
async publishRecord(recordData: any): Promise<any> {
const fee = parseGasAndFees(
this.registryConfig.fee.gas,
this.registryConfig.fee.fees,
);
const result = await registryTransactionWithRetry(() =>
this.registry.setRecord(
{
privateKey: this.registryConfig.privateKey,
record: recordData,
bondId: this.registryConfig.bondId,
},
this.registryConfig.privateKey,
fee,
),
);
return result;
}
async getRecordsByName(name: string): Promise<any> { async getRecordsByName(name: string): Promise<any> {
return this.registry.resolveNames([name]); return this.registry.resolveNames([name]);
} }

View File

@ -38,7 +38,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
}, },
deployments: async (_: any, { projectId }: { projectId: string }) => { deployments: async (_: any, { projectId }: { projectId: string }) => {
return service.getDeploymentsByProjectId(projectId); return service.getCommitDeploymentsByProjectId(projectId);
}, },
environmentVariables: async ( environmentVariables: async (
@ -95,6 +95,13 @@ export const createResolvers = async (service: Service): Promise<any> => {
) => { ) => {
return service.verifyTx(txHash, amount, senderAddress); return service.verifyTx(txHash, amount, senderAddress);
}, },
latestDNSRecord: async (
_: any,
{ projectId }: { projectId: string },
) => {
return service.getLatestDNSRecordByProjectId(projectId);
},
}, },
// TODO: Return error in GQL response // TODO: Return error in GQL response

View File

@ -108,6 +108,7 @@ type Deployment {
environment: Environment! environment: Environment!
deployer: Deployer deployer: Deployer
applicationDeploymentRequestId: String applicationDeploymentRequestId: String
applicationDeploymentRecordData: AppDeploymentRecordAttributes
isCurrent: Boolean! isCurrent: Boolean!
baseDomain: String baseDomain: String
status: DeploymentStatus! status: DeploymentStatus!
@ -249,6 +250,27 @@ type Auction {
bids: [Bid!]! bids: [Bid!]!
} }
type DNSRecordAttributes {
name: String
value: String
request: String
resourceType: String
version: String
}
type AppDeploymentRecordAttributes {
application: String
auction: String
deployer: String
dns: String
meta: String
name: String
request: String
type: String
url: String
version: String
}
input AuctionParams { input AuctionParams {
maxPrice: String, maxPrice: String,
numProviders: Int, numProviders: Int,
@ -265,6 +287,7 @@ type Query {
projectMembers(projectId: String!): [ProjectMember!] projectMembers(projectId: String!): [ProjectMember!]
searchProjects(searchText: String!): [Project!] searchProjects(searchText: String!): [Project!]
getAuctionData(auctionId: String!): Auction! getAuctionData(auctionId: String!): Auction!
latestDNSRecord(projectId: String!): DNSRecordAttributes
domains(projectId: String!, filter: FilterDomainsInput): [Domain] domains(projectId: String!, filter: FilterDomainsInput): [Domain]
deployers: [Deployer] deployers: [Deployer]
address: String! address: String!

View File

@ -1,7 +1,8 @@
import assert from 'assert'; import assert from 'assert';
import debug from 'debug'; import debug from 'debug';
import { DeepPartial, FindOptionsWhere, IsNull, Not } from 'typeorm'; import { DeepPartial, FindOptionsWhere } from 'typeorm';
import { Octokit, RequestError } from 'octokit'; import { Octokit, RequestError } from 'octokit';
import { DateTime } from 'luxon';
import { OAuthApp } from '@octokit/oauth-app'; import { OAuthApp } from '@octokit/oauth-app';
@ -22,6 +23,8 @@ import {
AppDeploymentRemovalRecord, AppDeploymentRemovalRecord,
AuctionParams, AuctionParams,
DeployerRecord, DeployerRecord,
DNSRecord,
DNSRecordAttributes,
EnvironmentVariables, EnvironmentVariables,
GitPushEventPayload, GitPushEventPayload,
} from './types'; } from './types';
@ -199,52 +202,114 @@ export class Service {
if (!deployment.project) { if (!deployment.project) {
log(`Project ${deployment.projectId} not found`); log(`Project ${deployment.projectId} not found`);
return; return;
} else { }
deployment.applicationDeploymentRecordId = record.id;
deployment.applicationDeploymentRecordData = record.attributes;
deployment.url = record.attributes.url;
deployment.status = DeploymentStatus.Ready;
deployment.isCurrent = deployment.environment === Environment.Production;
await this.db.updateDeploymentById(deployment.id, deployment); const registryRecord = await this.laconicRegistry.getRecordById(record.attributes.dns);
// Release deployer funds on successful deployment if (!registryRecord) {
if (!deployment.project.fundsReleased) { log(`DNS record not found for deployment ${deployment.id}`);
const fundsReleased = await this.releaseDeployerFundsByProjectId(deployment.projectId); return;
}
// Return remaining amount to owner const dnsRecord = registryRecord as DNSRecord;
await this.returnUserFundsByProjectId(deployment.projectId, true);
await this.db.updateProjectById(deployment.projectId, { const dnsRecordData: DNSRecordAttributes = {
fundsReleased, name: dnsRecord.attributes.name,
}); request: dnsRecord.attributes.request,
resourceType: dnsRecord.attributes.resource_type,
value: dnsRecord.attributes.value,
version: dnsRecord.attributes.version,
}
deployment.applicationDeploymentRecordId = record.id;
deployment.applicationDeploymentRecordData = record.attributes;
deployment.url = record.attributes.url;
deployment.status = DeploymentStatus.Ready;
deployment.isCurrent = deployment.environment === Environment.Production;
deployment.dnsRecordData = dnsRecordData;
if (deployment.isDNS) {
const oldDNSDeployment = await this.db.getDeployment({
where: {
projectId: deployment.project.id,
deployer: deployment.deployer,
isDNS: true,
isCurrent: true,
},
relations: {
project: true,
deployer: true,
}
});
if (oldDNSDeployment) {
// Send removal request for the previous DNS deployment and delete DB entry
if (oldDNSDeployment.url !== deployment.url) {
await this.laconicRegistry.createApplicationDeploymentRemovalRequest({
deploymentId: oldDNSDeployment.applicationDeploymentRecordId!,
deployerLrn: oldDNSDeployment.deployer.deployerLrn,
auctionId: oldDNSDeployment.project.auctionId,
payment: oldDNSDeployment.project.txHash
});
}
await this.db.deleteDeploymentById(oldDNSDeployment.id);
} }
log( // Update domain after the previous DNS deployment is deleted due to unique key constraint for domain
`Updated deployment ${deployment.id} with URL ${record.attributes.url}`, // Set the domain for the new current DNS deployment to the custom domain that was added for that project
); const customDomain = await this.db.getOldestDomainByProjectId(deployment.project.id);
if (customDomain) {
deployment.domain = customDomain;
}
} }
await this.db.updateDeploymentById(deployment.id, deployment);
// Release deployer funds on successful deployment
if (!deployment.project.fundsReleased) {
const fundsReleased = await this.releaseDeployerFundsByProjectId(deployment.projectId);
// Return remaining amount to owner
await this.returnUserFundsByProjectId(deployment.projectId, true);
await this.db.updateProjectById(deployment.projectId, {
fundsReleased,
});
}
log(
`Updated deployment ${deployment.id} with URL ${record.attributes.url}`,
);
}); });
await Promise.all(deploymentUpdatePromises); await Promise.all(deploymentUpdatePromises);
// Get deployments that are in production environment // Get deployments that are in production environment
const prodDeployments = Object.values(recordToDeploymentsMap).filter(deployment => deployment.isCurrent); const prodDeployments = Object.values(recordToDeploymentsMap).filter(
(deployment) => deployment.isCurrent,
);
// Set the isCurrent state to false for the old deployments // Set the isCurrent state to false for the old deployments
for (const deployment of prodDeployments) { for (const deployment of prodDeployments) {
const projectDeployments = await this.db.getDeploymentsByProjectId(deployment.projectId); const projectDeployments = await this.db.getDeploymentsByProjectId(
const oldDeployments = projectDeployments deployment.projectId,
.filter(projectDeployment => projectDeployment.deployer.deployerLrn === deployment.deployer.deployerLrn && projectDeployment.id !== deployment.id); );
const oldDeployments = projectDeployments.filter(
(projectDeployment) =>
projectDeployment.deployer.deployerLrn ===
deployment.deployer.deployerLrn &&
projectDeployment.id !== deployment.id &&
projectDeployment.isDNS == deployment.isDNS,
);
for (const oldDeployment of oldDeployments) { for (const oldDeployment of oldDeployments) {
await this.db.updateDeployment( await this.db.updateDeployment(
{ id: oldDeployment.id }, { id: oldDeployment.id },
{ isCurrent: false } { isCurrent: false },
); );
} }
} }
await Promise.all(deploymentUpdatePromises);
} }
/** /**
@ -428,9 +493,14 @@ export class Service {
return dbProjects; return dbProjects;
} }
async getDeploymentsByProjectId(projectId: string): Promise<Deployment[]> { async getCommitDeploymentsByProjectId(projectId: string): Promise<Deployment[]> {
const dbDeployments = await this.db.getDeploymentsByProjectId(projectId); const commitDeployments = await this.db.getCommitDeploymentsByProjectId(projectId);
return dbDeployments; return commitDeployments;
}
async getLatestDNSRecordByProjectId(projectId: string): Promise<DNSRecordAttributes | null> {
const dnsDeployments = await this.db.getLatestDNSRecordByProjectId(projectId);
return dnsDeployments;
} }
async getEnvironmentVariablesByProjectId( async getEnvironmentVariablesByProjectId(
@ -639,51 +709,62 @@ export class Service {
deployer = data.deployer; deployer = data.deployer;
} }
const newDeployment = await this.createDeploymentFromData(userId, data, deployer!.deployerLrn!, applicationRecordId, applicationRecordData); const deployment = await this.createDeploymentFromData(userId, data, deployer!.deployerLrn!, applicationRecordId, applicationRecordData, false);
const dnsDeployment = await this.createDeploymentFromData(userId, data, deployer!.deployerLrn!, applicationRecordId, applicationRecordData, true);
const address = await this.getAddress(); const address = await this.getAddress();
const { repo, repoUrl } = await getRepoDetails(octokit, data.project.repository, data.commitHash); const { repo, repoUrl } = await getRepoDetails(octokit, data.project.repository, data.commitHash);
const environmentVariablesObj = await this.getEnvVariables(data.project!.id!); const environmentVariablesObj = await this.getEnvVariables(data.project!.id!);
// If a custom domain is present then use that as the DNS in the deployment request
const customDomain = await this.db.getOldestDomainByProjectId(data.project!.id!);
// To set project DNS // To set project DNS
if (data.environment === Environment.Production) { if (data.environment === Environment.Production) {
// On deleting deployment later, project DNS deployment is also deleted // On deleting deployment later, project DNS deployment is also deleted
// So publish project DNS deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later // So publish project DNS deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later
await this.laconicRegistry.createApplicationDeploymentRequest({ const { applicationDeploymentRequestData, applicationDeploymentRequestId } =
deployment: newDeployment, await this.laconicRegistry.createApplicationDeploymentRequest({
appName: repo, deployment: dnsDeployment,
repository: repoUrl, appName: repo,
environmentVariables: environmentVariablesObj, repository: repoUrl,
dns: `${newDeployment.project.name}`, environmentVariables: environmentVariablesObj,
lrn: deployer!.deployerLrn!, dns: customDomain?.name ?? `${dnsDeployment.project.name}`,
apiUrl: deployer!.deployerApiUrl!, lrn: deployer!.deployerLrn!,
payment: data.project.txHash, apiUrl: deployer!.deployerApiUrl!,
auctionId: data.project.auctionId, payment: data.project.txHash,
requesterAddress: address, auctionId: data.project.auctionId,
publicKey: deployer!.publicKey! requesterAddress: address,
publicKey: deployer!.publicKey!
});
await this.db.updateDeploymentById(dnsDeployment.id, {
applicationDeploymentRequestId,
applicationDeploymentRequestData,
}); });
} }
const { applicationDeploymentRequestId, applicationDeploymentRequestData } = const { applicationDeploymentRequestId, applicationDeploymentRequestData } =
await this.laconicRegistry.createApplicationDeploymentRequest({ await this.laconicRegistry.createApplicationDeploymentRequest({
deployment: newDeployment, deployment: deployment,
appName: repo, appName: repo,
repository: repoUrl, repository: repoUrl,
lrn: deployer!.deployerLrn!, lrn: deployer!.deployerLrn!,
apiUrl: deployer!.deployerApiUrl!, apiUrl: deployer!.deployerApiUrl!,
environmentVariables: environmentVariablesObj, environmentVariables: environmentVariablesObj,
dns: `${newDeployment.project.name}-${newDeployment.id}`, dns: `${deployment.project.name}-${deployment.id}`,
payment: data.project.txHash, payment: data.project.txHash,
auctionId: data.project.auctionId, auctionId: data.project.auctionId,
requesterAddress: address, requesterAddress: address,
publicKey: deployer!.publicKey! publicKey: deployer!.publicKey!
}); });
await this.db.updateDeploymentById(newDeployment.id, { await this.db.updateDeploymentById(deployment.id, {
applicationDeploymentRequestId, applicationDeploymentRequestId,
applicationDeploymentRequestData, applicationDeploymentRequestData,
}); });
return newDeployment; return deployment;
} }
async createDeploymentFromAuction( async createDeploymentFromAuction(
@ -726,7 +807,8 @@ export class Service {
commitMessage: latestCommit.commit.message, commitMessage: latestCommit.commit.message,
}; };
const newDeployment = await this.createDeploymentFromData(project.ownerId!, deploymentData, deployerLrn, applicationRecordId, applicationRecordData); const deployment = await this.createDeploymentFromData(project.ownerId!, deploymentData, deployerLrn, applicationRecordId, applicationRecordData, false);
const dnsDeployment = await this.createDeploymentFromData(project.ownerId!, deploymentData, deployerLrn, applicationRecordId, applicationRecordData, true);
const address = await this.getAddress(); const address = await this.getAddress();
const environmentVariablesObj = await this.getEnvVariables(project!.id!); const environmentVariablesObj = await this.getEnvVariables(project!.id!);
@ -734,41 +816,47 @@ export class Service {
if (deploymentData.environment === Environment.Production) { if (deploymentData.environment === Environment.Production) {
// On deleting deployment later, project DNS deployment is also deleted // On deleting deployment later, project DNS deployment is also deleted
// So publish project DNS deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later // So publish project DNS deployment first so that ApplicationDeploymentRecord for the same is available when deleting deployment later
await this.laconicRegistry.createApplicationDeploymentRequest({ const { applicationDeploymentRequestId, applicationDeploymentRequestData } =
deployment: newDeployment, await this.laconicRegistry.createApplicationDeploymentRequest({
appName: repo, deployment: dnsDeployment,
repository: repoUrl, appName: repo,
environmentVariables: environmentVariablesObj, repository: repoUrl,
dns: `${newDeployment.project.name}`, environmentVariables: environmentVariablesObj,
auctionId: project.auctionId!, dns: `${dnsDeployment.project.name}`,
lrn: deployerLrn, auctionId: project.auctionId!,
apiUrl: deployer!.deployerApiUrl!, lrn: deployerLrn,
requesterAddress: address, apiUrl: deployer!.deployerApiUrl!,
publicKey: deployer!.publicKey! requesterAddress: address,
publicKey: deployer!.publicKey!
});
await this.db.updateDeploymentById(dnsDeployment.id, {
applicationDeploymentRequestId,
applicationDeploymentRequestData,
}); });
} }
const { applicationDeploymentRequestId, applicationDeploymentRequestData } = const { applicationDeploymentRequestId, applicationDeploymentRequestData } =
// Create requests for all the deployers // Create requests for all the deployers
await this.laconicRegistry.createApplicationDeploymentRequest({ await this.laconicRegistry.createApplicationDeploymentRequest({
deployment: newDeployment, deployment: deployment,
appName: repo, appName: repo,
repository: repoUrl, repository: repoUrl,
auctionId: project.auctionId!, auctionId: project.auctionId!,
lrn: deployerLrn, lrn: deployerLrn,
apiUrl: deployer!.deployerApiUrl!, apiUrl: deployer!.deployerApiUrl!,
environmentVariables: environmentVariablesObj, environmentVariables: environmentVariablesObj,
dns: `${newDeployment.project.name}-${newDeployment.id}`, dns: `${deployment.project.name}-${deployment.id}`,
requesterAddress: address, requesterAddress: address,
publicKey: deployer!.publicKey! publicKey: deployer!.publicKey!
}); });
await this.db.updateDeploymentById(newDeployment.id, { await this.db.updateDeploymentById(deployment.id, {
applicationDeploymentRequestId, applicationDeploymentRequestId,
applicationDeploymentRequestData, applicationDeploymentRequestData,
}); });
return newDeployment; return deployment;
} }
async createDeploymentFromData( async createDeploymentFromData(
@ -777,6 +865,7 @@ export class Service {
deployerLrn: string, deployerLrn: string,
applicationRecordId: string, applicationRecordId: string,
applicationRecordData: ApplicationRecord, applicationRecordData: ApplicationRecord,
isDNS: boolean,
): Promise<Deployment> { ): Promise<Deployment> {
const newDeployment = await this.db.addDeployment({ const newDeployment = await this.db.addDeployment({
project: data.project, project: data.project,
@ -794,6 +883,7 @@ export class Service {
deployer: Object.assign(new Deployer(), { deployer: Object.assign(new Deployer(), {
deployerLrn, deployerLrn,
}), }),
isDNS
}); });
log(`Created deployment ${newDeployment.id}`); log(`Created deployment ${newDeployment.id}`);
@ -1133,17 +1223,20 @@ export class Service {
const oldCurrentDeployment = await this.db.getDeployment({ const oldCurrentDeployment = await this.db.getDeployment({
relations: { relations: {
domain: true, domain: true,
project: true,
deployer: true,
}, },
where: { where: {
project: { project: {
id: projectId, id: projectId,
}, },
isCurrent: true, isCurrent: true,
isDNS: false,
}, },
}); });
if (!oldCurrentDeployment) { if (!oldCurrentDeployment) {
throw new Error('Current deployment doesnot exist'); throw new Error('Current deployment does not exist');
} }
const oldCurrentDeploymentUpdate = await this.db.updateDeploymentById( const oldCurrentDeploymentUpdate = await this.db.updateDeploymentById(
@ -1153,9 +1246,46 @@ export class Service {
const newCurrentDeploymentUpdate = await this.db.updateDeploymentById( const newCurrentDeploymentUpdate = await this.db.updateDeploymentById(
deploymentId, deploymentId,
{ isCurrent: true, domain: oldCurrentDeployment?.domain }, { isCurrent: true, domain: oldCurrentDeployment.domain },
); );
const newCurrentDeployment = await this.db.getDeployment({ where: { id: deploymentId }, relations: { project: true, deployer: true } });
if (!newCurrentDeployment) {
throw new Error(`Deployment with Id ${deploymentId} not found`);
}
// Create a DNS deployment for the new current deployment
const dnsDeployment = await this.createDeploymentFromData(
newCurrentDeployment.project.ownerId,
newCurrentDeployment,
newCurrentDeployment.deployer!.deployerLrn!,
newCurrentDeployment.applicationRecordId,
newCurrentDeployment.applicationRecordData,
true,
);
const applicationDeploymentRequestData = newCurrentDeployment.applicationDeploymentRequestData;
applicationDeploymentRequestData!.version = (Number(applicationDeploymentRequestData?.version) + 1).toString();
applicationDeploymentRequestData!.meta = JSON.stringify({
...JSON.parse(applicationDeploymentRequestData!.meta),
note: `Updated by Snowball @ ${DateTime.utc().toFormat(
"EEE LLL dd HH:mm:ss 'UTC' yyyy"
)}`
});
const result = await this.laconicRegistry.publishRecord(
applicationDeploymentRequestData,
);
log(`Application deployment request record published: ${result.id}`)
await this.db.updateDeploymentById(dnsDeployment.id, {
applicationDeploymentRequestId: result.id,
applicationDeploymentRequestData,
});
return newCurrentDeploymentUpdate && oldCurrentDeploymentUpdate; return newCurrentDeploymentUpdate && oldCurrentDeploymentUpdate;
} }
@ -1173,32 +1303,38 @@ export class Service {
if (deployment && deployment.applicationDeploymentRecordId) { if (deployment && deployment.applicationDeploymentRecordId) {
// If deployment is current, remove deployment for project subdomain as well // If deployment is current, remove deployment for project subdomain as well
if (deployment.isCurrent) { if (deployment.isCurrent) {
const currentDeploymentURL = `https://${(deployment.project.name).toLowerCase()}.${deployment.deployer.baseDomain}`; const dnsDeployment = await this.db.getDeployment({
where: {
projectId: deployment.project.id,
deployer: deployment.deployer,
isDNS: true
},
relations: {
project: true,
deployer: true,
},
})
// TODO: Store the latest DNS deployment record if (!dnsDeployment) {
const deploymentRecords = log(`DNS deployment for deployment with id ${deployment.id} not found`);
await this.laconicRegistry.getDeploymentRecordsByFilter({
application: deployment.applicationRecordId,
url: currentDeploymentURL,
});
if (!deploymentRecords.length) {
log(
`No ApplicationDeploymentRecord found for URL ${currentDeploymentURL} and ApplicationDeploymentRecord id ${deployment.applicationDeploymentRecordId}`,
);
return false; return false;
} }
// Multiple records are fetched, take the latest record const dnsResult =
const latestRecord = deploymentRecords await this.laconicRegistry.createApplicationDeploymentRemovalRequest({
.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())[0]; deploymentId: dnsDeployment.applicationDeploymentRecordId!,
deployerLrn: dnsDeployment.deployer.deployerLrn,
auctionId: dnsDeployment.project.auctionId,
payment: dnsDeployment.project.txHash
});
await this.laconicRegistry.createApplicationDeploymentRemovalRequest({ await this.db.updateDeploymentById(dnsDeployment.id, {
deploymentId: latestRecord.id, status: DeploymentStatus.Deleting,
deployerLrn: deployment.deployer.deployerLrn, applicationDeploymentRemovalRequestId:
auctionId: deployment.project.auctionId, dnsResult.applicationDeploymentRemovalRequestId,
payment: deployment.project.txHash applicationDeploymentRemovalRequestData:
dnsResult.applicationDeploymentRemovalRequestData,
}); });
} }
@ -1229,7 +1365,7 @@ export class Service {
data: { name: string }, data: { name: string },
): Promise<{ ): Promise<{
primaryDomain: Domain; primaryDomain: Domain;
redirectedDomain: Domain; // redirectedDomain: Domain;
}> { }> {
const currentProject = await this.db.getProjectById(projectId); const currentProject = await this.db.getProjectById(projectId);
@ -1245,22 +1381,22 @@ export class Service {
const savedPrimaryDomain = await this.db.addDomain(primaryDomainDetails); const savedPrimaryDomain = await this.db.addDomain(primaryDomainDetails);
const domainArr = data.name.split('www.'); // const domainArr = data.name.split('www.');
const redirectedDomainDetails = { // const redirectedDomainDetails = {
name: domainArr.length > 1 ? domainArr[1] : `www.${domainArr[0]}`, // name: domainArr.length > 1 ? domainArr[1] : `www.${domainArr[0]}`,
branch: currentProject.prodBranch, // branch: currentProject.prodBranch,
project: currentProject, // project: currentProject,
redirectTo: savedPrimaryDomain, // redirectTo: savedPrimaryDomain,
}; // };
const savedRedirectedDomain = await this.db.addDomain( // const savedRedirectedDomain = await this.db.addDomain(
redirectedDomainDetails, // redirectedDomainDetails,
); // );
return { return {
primaryDomain: savedPrimaryDomain, primaryDomain: savedPrimaryDomain,
redirectedDomain: savedRedirectedDomain, // redirectedDomain: savedRedirectedDomain,
}; };
} }

View File

@ -40,6 +40,22 @@ export interface AppDeploymentRecordAttributes {
version: string; version: string;
} }
export interface DNSRecordAttributes {
name: string;
value: string;
request: string;
resourceType: string;
version: string;
}
export interface RegistryDNSRecordAttributes {
name: string;
value: string;
request: string;
resource_type: string;
version: string;
}
export interface AppDeploymentRemovalRecordAttributes { export interface AppDeploymentRemovalRecordAttributes {
deployment: string; deployment: string;
request: string; request: string;
@ -47,7 +63,7 @@ export interface AppDeploymentRemovalRecordAttributes {
version: string; version: string;
} }
interface RegistryRecord { export interface RegistryRecord {
id: string; id: string;
names: string[] | null; names: string[] | null;
owners: string[]; owners: string[];
@ -64,6 +80,10 @@ export interface AppDeploymentRemovalRecord extends RegistryRecord {
attributes: AppDeploymentRemovalRecordAttributes; attributes: AppDeploymentRemovalRecordAttributes;
} }
export interface DNSRecord extends RegistryRecord {
attributes: RegistryDNSRecordAttributes
}
export interface AddProjectFromTemplateInput { export interface AddProjectFromTemplateInput {
templateOwner: string; templateOwner: string;
templateRepo: string; templateRepo: string;

View File

@ -4,7 +4,11 @@ import {
MenuItem, MenuItem,
MenuList, MenuList,
} from '@snowballtools/material-tailwind-react-fork'; } from '@snowballtools/material-tailwind-react-fork';
import { ComponentPropsWithoutRef, MouseEvent, useCallback } from 'react'; import {
ComponentPropsWithoutRef,
MouseEvent,
useCallback,
} from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Project } from 'gql-client'; import { Project } from 'gql-client';
import { Avatar } from 'components/shared/Avatar'; import { Avatar } from 'components/shared/Avatar';
@ -83,7 +87,7 @@ export const ProjectCard = ({
<p className={theme.title()}>{project.name}</p> <p className={theme.title()}>{project.name}</p>
</Tooltip> </Tooltip>
<p className={theme.description()}> <p className={theme.description()}>
{project.deployments[0]?.domain?.name ?? 'No domain'} {project.deployments[0]?.applicationDeploymentRecordData?.url ?? 'No domain'}
</p> </p>
</div> </div>
{/* Icons */} {/* Icons */}

View File

@ -566,7 +566,7 @@ const Configure = () => {
<Button <Button
{...buttonSize} {...buttonSize}
type="submit" type="submit"
disabled={isLoading || !selectedDeployer || !selectedAccount} disabled={isLoading || !selectedDeployer}
rightIcon={ rightIcon={
isLoading ? ( isLoading ? (
<LoadingIcon className="animate-spin" /> <LoadingIcon className="animate-spin" />

View File

@ -1,5 +1,5 @@
import { useState } from 'react'; import { useEffect, useState } from 'react';
import { Domain, DomainStatus, Project } from 'gql-client'; import { DNSRecordAttributes, Domain, DomainStatus, Project } from 'gql-client';
import { import {
Typography, Typography,
@ -14,22 +14,27 @@ import EditDomainDialog from './EditDomainDialog';
import { useGQLClient } from 'context/GQLClientContext'; import { useGQLClient } from 'context/GQLClientContext';
import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog'; import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog';
import { useToast } from 'components/shared/Toast'; import { useToast } from 'components/shared/Toast';
import { Tag } from 'components/shared/Tag'; import { GearIcon } from 'components/shared/CustomIcon';
import {
CheckIcon,
CrossIcon,
GearIcon,
LoadingIcon,
} from 'components/shared/CustomIcon';
import { Heading } from 'components/shared/Heading'; import { Heading } from 'components/shared/Heading';
import { Button } from 'components/shared/Button'; import { Button } from 'components/shared/Button';
import { useParams } from 'react-router-dom';
enum RefreshStatus { // NOTE: Commented code for verify domain functionality
IDLE, // import { Tag } from 'components/shared/Tag';
CHECKING, // import {
CHECK_SUCCESS, // CheckIcon,
CHECK_FAIL, // CrossIcon,
} // LoadingIcon,
// } from 'components/shared/CustomIcon';
// enum RefreshStatus {
// IDLE,
// CHECKING,
// CHECK_SUCCESS,
// CHECK_FAIL,
// }
// const CHECK_FAIL_TIMEOUT = 5000; // In milliseconds
interface DomainCardProps { interface DomainCardProps {
domains: Domain[]; domains: Domain[];
@ -39,14 +44,6 @@ interface DomainCardProps {
onUpdate: () => Promise<void>; onUpdate: () => Promise<void>;
} }
const CHECK_FAIL_TIMEOUT = 5000; // In milliseconds
// TODO: Get domain record
const DOMAIN_RECORD = {
type: 'A',
name: '@',
value: '56.49.19.21',
};
const DomainCard = ({ const DomainCard = ({
domains, domains,
@ -56,9 +53,11 @@ const DomainCard = ({
onUpdate, onUpdate,
}: DomainCardProps) => { }: DomainCardProps) => {
const { toast, dismiss } = useToast(); const { toast, dismiss } = useToast();
const [refreshStatus, SetRefreshStatus] = useState(RefreshStatus.IDLE); const { id } = useParams();
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [editDialogOpen, setEditDialogOpen] = useState(false); const [editDialogOpen, setEditDialogOpen] = useState(false);
const [dnsRecord, setDnsRecord] = useState<DNSRecordAttributes | null>(null);
// const [refreshStatus, SetRefreshStatus] = useState(RefreshStatus.IDLE);
const client = useGQLClient(); const client = useGQLClient();
@ -83,13 +82,33 @@ const DomainCard = ({
} }
}; };
useEffect(() => {
const fetchDNSData = async () => {
if (id === undefined) {
toast({
id: 'domain_cannot_find_project',
title: 'Cannot find project',
variant: 'error',
onDismiss: dismiss,
});
return;
}
const dnsRecordResponse = await client.getLatestDNSRecordByProjectId(id);
setDnsRecord(dnsRecordResponse.latestDNSRecord);
};
fetchDNSData();
}, [id, client]);
return ( return (
<> <>
<div className="flex justify-between py-3"> <div className="flex justify-between py-3">
<div className="flex justify-start gap-1"> <div className="flex justify-start gap-1">
<Heading as="h6" className="flex-col"> <Heading as="h6" className="flex-col">
{domain.name}{' '} {domain.name}{' '}
<Tag {/* <Tag
type={ type={
domain.status === DomainStatus.Live ? 'positive' : 'negative' domain.status === DomainStatus.Live ? 'positive' : 'negative'
} }
@ -102,12 +121,12 @@ const DomainCard = ({
} }
> >
{domain.status} {domain.status}
</Tag> </Tag> */}
</Heading> </Heading>
</div> </div>
<div className="flex justify-start gap-1"> <div className="flex justify-start gap-1">
<i {/* <i
id="refresh" id="refresh"
className="cursor-pointer" className="cursor-pointer"
onClick={() => { onClick={() => {
@ -122,7 +141,7 @@ const DomainCard = ({
) : ( ) : (
'L' 'L'
)} )}
</i> </i> */}
<Menu placement="bottom-end"> <Menu placement="bottom-end">
<MenuHandler> <MenuHandler>
<Button iconOnly> <Button iconOnly>
@ -163,11 +182,11 @@ const DomainCard = ({
<Typography variant="small">Production</Typography> <Typography variant="small">Production</Typography>
{domain.status === DomainStatus.Pending && ( {domain.status === DomainStatus.Pending && (
<Card className="bg-slate-100 p-4 text-sm"> <Card className="bg-slate-100 p-4 text-sm">
{refreshStatus === RefreshStatus.IDLE ? ( {/* {refreshStatus === RefreshStatus.IDLE ? ( */}
<Heading> <Heading>
^ Add these records to your domain and refresh to check ^ Add these records to your domain {/* and refresh to check */}
</Heading> </Heading>
) : refreshStatus === RefreshStatus.CHECKING ? ( {/* ) : refreshStatus === RefreshStatus.CHECKING ? (
<Heading className="text-blue-500"> <Heading className="text-blue-500">
^ Checking records for {domain.name} ^ Checking records for {domain.name}
</Heading> </Heading>
@ -178,7 +197,7 @@ const DomainCard = ({
hours. Please ensure you added the correct records and refresh. hours. Please ensure you added the correct records and refresh.
</div> </div>
</div> </div>
)} )} */}
<table> <table>
<thead> <thead>
@ -189,11 +208,15 @@ const DomainCard = ({
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr> {dnsRecord ? (
<td>{DOMAIN_RECORD.type}</td> <tr>
<td>{DOMAIN_RECORD.name}</td> <td>{dnsRecord.resourceType}</td>
<td>{DOMAIN_RECORD.value}</td> <td>@</td>
</tr> <td>{dnsRecord.value ?? 'Not Configured'}</td>
</tr>
) : (
<p className={'text-red-500'}>DNS record data not available</p>
)}
</tbody> </tbody>
</table> </table>
</Card> </Card>

View File

@ -1,11 +1,15 @@
import { useCallback, useEffect, useMemo } from 'react'; import {
import { Controller, useForm, SubmitHandler } from 'react-hook-form'; useCallback,
useEffect,
} from 'react';
import {
useForm,
SubmitHandler,
} from 'react-hook-form';
import { Domain } from 'gql-client'; import { Domain } from 'gql-client';
import { import {
Typography, Typography,
Select,
Option,
} from '@snowballtools/material-tailwind-react-fork'; } from '@snowballtools/material-tailwind-react-fork';
import { useGQLClient } from 'context/GQLClientContext'; import { useGQLClient } from 'context/GQLClientContext';
@ -14,7 +18,15 @@ import { Button } from 'components/shared/Button';
import { Input } from 'components/shared/Input'; import { Input } from 'components/shared/Input';
import { useToast } from 'components/shared/Toast'; import { useToast } from 'components/shared/Toast';
const DEFAULT_REDIRECT_OPTIONS = ['none']; // NOTE: Commented code for redirect domain functionality
// import {
// Select,
// Option,
// } from '@snowballtools/material-tailwind-react-fork';
// import { Controller } from 'react-hook-form';
// import { useMemo } from 'react';
// const DEFAULT_REDIRECT_OPTIONS = ['none'];
interface EditDomainDialogProp { interface EditDomainDialogProp {
domains: Domain[]; domains: Domain[];
@ -28,7 +40,7 @@ interface EditDomainDialogProp {
type EditDomainValues = { type EditDomainValues = {
name: string; name: string;
branch: string; branch: string;
redirectedTo: string; // redirectedTo: string;
}; };
const EditDomainDialog = ({ const EditDomainDialog = ({
@ -42,58 +54,58 @@ const EditDomainDialog = ({
const client = useGQLClient(); const client = useGQLClient();
const { toast, dismiss } = useToast(); const { toast, dismiss } = useToast();
const getRedirectUrl = (domain: Domain) => { // const getRedirectUrl = (domain: Domain) => {
const redirectDomain = domain.redirectTo; // const redirectDomain = domain.redirectTo;
if (redirectDomain !== null) { // if (redirectDomain !== null) {
return redirectDomain?.name; // return redirectDomain?.name;
} else { // } else {
return 'none'; // return 'none';
} // }
}; // };
const redirectOptions = useMemo(() => { // const redirectOptions = useMemo(() => {
const domainNames = domains // const domainNames = domains
.filter((domainData) => domainData.id !== domain.id) // .filter((domainData) => domainData.id !== domain.id)
.map((domain) => domain.name); // .map((domain) => domain.name);
return ['none', ...domainNames]; // return ['none', ...domainNames];
}, [domain, domains]); // }, [domain, domains]);
const domainRedirectedFrom = useMemo(() => { // const domainRedirectedFrom = useMemo(() => {
return domains.find( // return domains.find(
(domainData) => domainData.redirectTo?.id === domain.id, // (domainData) => domainData.redirectTo?.id === domain.id,
); // );
}, [domains, domain]); // }, [domains, domain]);
const isDisableDropdown = useMemo(() => { // const isDisableDropdown = useMemo(() => {
return domainRedirectedFrom !== undefined; // return domainRedirectedFrom !== undefined;
}, [domain, domains]); // }, [domain, domains]);
const { const {
handleSubmit, handleSubmit,
register, register,
control, // control,
watch, // watch,
reset, reset,
formState: { isValid, isDirty }, formState: { isValid, isDirty },
} = useForm({ } = useForm({
defaultValues: { defaultValues: {
name: domain.name, name: domain.name,
branch: domain.branch, branch: domain.branch,
redirectedTo: getRedirectUrl(domain), // redirectedTo: getRedirectUrl(domain),
}, },
}); });
const updateDomainHandler: SubmitHandler<EditDomainValues> = useCallback( const updateDomainHandler: SubmitHandler<EditDomainValues> = useCallback(
async (data) => { async (data) => {
const domainRedirectTo = domains.find( // const domainRedirectTo = domains.find(
(domainData) => data.redirectedTo === domainData.name, // (domainData) => data.redirectedTo === domainData.name,
); // );
const updates = { const updates = {
name: data.name ? data.name : domain.name, name: data.name ? data.name : domain.name,
branch: data.branch ? data.branch : domain.branch, branch: data.branch ? data.branch : domain.branch,
redirectToId: domainRedirectTo ? domainRedirectTo.id : null, // redirectToId: domainRedirectTo ? domainRedirectTo.id : null,
}; };
const { updateDomain } = await client.updateDomain(domain.id, updates); const { updateDomain } = await client.updateDomain(domain.id, updates);
@ -125,7 +137,7 @@ const EditDomainDialog = ({
reset({ reset({
name: domain.name, name: domain.name,
branch: domain.branch, branch: domain.branch,
redirectedTo: getRedirectUrl(domain), // redirectedTo: getRedirectUrl(domain),
}); });
}, [domain]); }, [domain]);
@ -137,7 +149,7 @@ const EditDomainDialog = ({
<Modal.Body className="flex flex-col gap-2"> <Modal.Body className="flex flex-col gap-2">
<Typography variant="small">Domain name</Typography> <Typography variant="small">Domain name</Typography>
<Input {...register('name')} /> <Input {...register('name')} />
<Typography variant="small">Redirect to</Typography> {/* <Typography variant="small">Redirect to</Typography>
<Controller <Controller
name="redirectedTo" name="redirectedTo"
control={control} control={control}
@ -161,7 +173,7 @@ const EditDomainDialog = ({
further. further.
</Typography> </Typography>
</div> </div>
)} )} */}
<Typography variant="small">Git branch</Typography> <Typography variant="small">Git branch</Typography>
<Input <Input
{...register('branch', { {...register('branch', {
@ -169,8 +181,8 @@ const EditDomainDialog = ({
Boolean(branches.length) ? branches.includes(value) : true, Boolean(branches.length) ? branches.includes(value) : true,
})} })}
disabled={ disabled={
!Boolean(branches.length) || !Boolean(branches.length)
watch('redirectedTo') !== DEFAULT_REDIRECT_OPTIONS[0] // || watch('redirectedTo') !== DEFAULT_REDIRECT_OPTIONS[0]
} }
/> />
{!isValid && ( {!isValid && (

View File

@ -1,12 +1,14 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { Heading } from 'components/shared/Heading'; import { Heading } from 'components/shared/Heading';
import { InlineNotification } from 'components/shared/InlineNotification';
import { Input } from 'components/shared/Input'; import { Input } from 'components/shared/Input';
import { Button } from 'components/shared/Button'; import { Button } from 'components/shared/Button';
import { Radio } from 'components/shared/Radio';
// NOTE: Commented code for redirect domain functionality
// import { useEffect, useState } from 'react';
// import { InlineNotification } from 'components/shared/InlineNotification';
// import { Radio } from 'components/shared/Radio';
interface SetupDomainFormValues { interface SetupDomainFormValues {
domainName: string; domainName: string;
@ -18,47 +20,45 @@ const SetupDomain = () => {
register, register,
handleSubmit, handleSubmit,
formState: { isValid }, formState: { isValid },
watch, // watch,
setValue, // setValue,
} = useForm<SetupDomainFormValues>({ } = useForm<SetupDomainFormValues>({
defaultValues: { defaultValues: {
domainName: '', domainName: '',
isWWW: 'false', // isWWW: 'false',
}, },
mode: 'onChange', mode: 'onChange',
}); });
const [domainStr, setDomainStr] = useState<string>('');
const navigate = useNavigate(); const navigate = useNavigate();
const isWWWRadioOptions = [ // const [domainStr, setDomainStr] = useState<string>('');
{ label: domainStr, value: 'false' }, // const isWWWRadioOptions = [
{ label: `www.${domainStr}`, value: 'true' }, // { label: domainStr, value: 'false' },
]; // { label: `www.${domainStr}`, value: 'true' },
// ];
useEffect(() => { // useEffect(() => {
const subscription = watch((value, { name }) => { // const subscription = watch((value, { name }) => {
if (name === 'domainName' && value.domainName) { // if (name === 'domainName' && value.domainName) {
const domainArr = value.domainName.split('www.'); // const domainArr = value.domainName.split('www.');
const cleanedDomain = // const cleanedDomain =
domainArr.length > 1 ? domainArr[1] : domainArr[0]; // domainArr.length > 1 ? domainArr[1] : domainArr[0];
setDomainStr(cleanedDomain); // setDomainStr(cleanedDomain);
setValue( // setValue(
'isWWW', // 'isWWW',
value.domainName.startsWith('www.') ? 'true' : 'false', // value.domainName.startsWith('www.') ? 'true' : 'false',
); // );
} // }
}); // });
return () => subscription.unsubscribe(); // return () => subscription.unsubscribe();
}, [watch, setValue]); // }, [watch, setValue]);
return ( return (
<form <form
onSubmit={handleSubmit(() => { onSubmit={handleSubmit((e) => {
watch('isWWW') === 'true' navigate(`config?name=${e.domainName}`)
? navigate(`config?name=www.${domainStr}`)
: navigate(`config?name=${domainStr}`);
})} })}
className="flex flex-col gap-6 w-full" className="flex flex-col gap-6 w-full"
> >
@ -67,7 +67,7 @@ const SetupDomain = () => {
Setup domain name Setup domain name
</Heading> </Heading>
<p className="text-slate-500 text-sm font-normal leading-tight"> <p className="text-slate-500 text-sm font-normal leading-tight">
Add your domain and setup redirects Add your domain {/* and setup redirects */}
</p> </p>
</div> </div>
@ -80,7 +80,7 @@ const SetupDomain = () => {
label="Domain name" label="Domain name"
/> />
{isValid && ( {/* {isValid && (
<div className="self-stretch flex flex-col gap-4"> <div className="self-stretch flex flex-col gap-4">
<Heading className="text-sky-950 text-lg font-medium leading-normal"> <Heading className="text-sky-950 text-lg font-medium leading-normal">
Primary domain Primary domain
@ -99,7 +99,7 @@ const SetupDomain = () => {
}. Redirect preferences can be changed later`} }. Redirect preferences can be changed later`}
/> />
</div> </div>
)} )} */}
<div className="self-stretch"> <div className="self-stretch">
<Button disabled={!isValid} type="submit" shape="default"> <Button disabled={!isValid} type="submit" shape="default">

View File

@ -10,6 +10,7 @@ import { DeleteVariableDialog } from 'components/projects/Dialog/DeleteVariableD
import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog'; import { DeleteDomainDialog } from 'components/projects/Dialog/DeleteDomainDialog';
import { CancelDeploymentDialog } from 'components/projects/Dialog/CancelDeploymentDialog'; import { CancelDeploymentDialog } from 'components/projects/Dialog/CancelDeploymentDialog';
import { import {
AppDeploymentRecordAttributes,
Deployment, Deployment,
DeploymentStatus, DeploymentStatus,
Domain, Domain,
@ -57,6 +58,7 @@ const deployment: Deployment = {
updatedAt: '1677680400', // 2023-03-01T13:00:00Z updatedAt: '1677680400', // 2023-03-01T13:00:00Z
applicationDeploymentRequestId: applicationDeploymentRequestId:
'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize', 'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize',
applicationDeploymentRecordData: {} as AppDeploymentRecordAttributes,
}; };
const domains: Domain[] = [ const domains: Domain[] = [

View File

@ -1,39 +1,54 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Link, useNavigate, useOutletContext } from 'react-router-dom'; import {
Link,
useOutletContext,
} from 'react-router-dom';
import { RequestError } from 'octokit'; import { RequestError } from 'octokit';
import { useOctokit } from 'context/OctokitContext'; import {
import { GitCommitWithBranch, OutletContextType } from '../../../../types'; Heading,
import { useGQLClient } from 'context/GQLClientContext'; Avatar,
import { Button, Heading, Avatar, Tag } from 'components/shared'; } from 'components/shared';
import { getInitials } from 'utils/geInitials';
import { import {
BranchStrokeIcon, BranchStrokeIcon,
CheckRoundFilledIcon,
ClockIcon,
CursorBoxIcon, CursorBoxIcon,
GithubStrokeIcon, GithubStrokeIcon,
GlobeIcon,
LinkIcon, LinkIcon,
CalendarDaysIcon, CalendarDaysIcon,
} from 'components/shared/CustomIcon'; } from 'components/shared/CustomIcon';
import { useOctokit } from 'context/OctokitContext';
import { GitCommitWithBranch, OutletContextType } from '../../../../types';
import { getInitials } from 'utils/geInitials';
import { Activity } from 'components/projects/project/overview/Activity'; import { Activity } from 'components/projects/project/overview/Activity';
import { OverviewInfo } from 'components/projects/project/overview/OverviewInfo'; import { OverviewInfo } from 'components/projects/project/overview/OverviewInfo';
import { relativeTimeMs } from 'utils/time'; import { relativeTimeMs } from 'utils/time';
import { Domain, DomainStatus } from 'gql-client';
import { AuctionCard } from 'components/projects/project/overview/Activity/AuctionCard'; import { AuctionCard } from 'components/projects/project/overview/Activity/AuctionCard';
// NOTE: Commented code for verify domain functionality
// import { useGQLClient } from 'context/GQLClientContext';
// import { Domain, DomainStatus } from 'gql-client';
// import {
// CheckRoundFilledIcon,
// ClockIcon,
// GlobeIcon,
// } from 'components/shared/CustomIcon';
// import {
// Button,
// Tag,
// } from 'components/shared';
// import { useNavigate } from 'react-router-dom';
const COMMITS_PER_PAGE = 4; const COMMITS_PER_PAGE = 4;
const PROJECT_UPDATE_WAIT_MS = 5000; const PROJECT_UPDATE_WAIT_MS = 5000;
const OverviewTabPanel = () => { const OverviewTabPanel = () => {
const { octokit } = useOctokit(); const { octokit } = useOctokit();
const navigate = useNavigate(); // const navigate = useNavigate();
const [activities, setActivities] = useState<GitCommitWithBranch[]>([]); const [activities, setActivities] = useState<GitCommitWithBranch[]>([]);
const [fetchingActivities, setFetchingActivities] = useState(true); const [fetchingActivities, setFetchingActivities] = useState(true);
const [liveDomain, setLiveDomain] = useState<Domain>(); // const [liveDomain, setLiveDomain] = useState<Domain>();
const client = useGQLClient(); // const client = useGQLClient();
const { project, onUpdate } = useOutletContext<OutletContextType>(); const { project, onUpdate } = useOutletContext<OutletContextType>();
useEffect(() => { useEffect(() => {
@ -107,22 +122,22 @@ const OverviewTabPanel = () => {
return () => clearInterval(timerId); return () => clearInterval(timerId);
}, [onUpdate]); }, [onUpdate]);
useEffect(() => { // useEffect(() => {
const fetchLiveProdDomain = async () => { // const fetchLiveProdDomain = async () => {
const { domains } = await client.getDomains(project.id, { // const { domains } = await client.getDomains(project.id, {
branch: project.prodBranch, // branch: project.prodBranch,
status: DomainStatus.Live, // status: DomainStatus.Live,
}); // });
if (domains.length === 0) { // if (domains.length === 0) {
return; // return;
} // }
setLiveDomain(domains[0]); // setLiveDomain(domains[0]);
}; // };
fetchLiveProdDomain(); // fetchLiveProdDomain();
}, [project]); // }, [project]);
return ( return (
<div className="grid grid-cols-5 gap-6 md:gap-[72px]"> <div className="grid grid-cols-5 gap-6 md:gap-[72px]">
@ -141,19 +156,16 @@ const OverviewTabPanel = () => {
{project.deployments && {project.deployments &&
project.deployments.length > 0 && project.deployments.length > 0 &&
project.deployments.map((deployment, index) => ( project.deployments.map((deployment, index) => (
<p> <p
<a key={index}
key={index} className="text-sm text-elements-low-em dark:text-foreground tracking-tight truncate"
href={`https://${project.name.toLowerCase()}.${deployment.deployer.baseDomain}`} >
className="text-sm text-elements-low-em dark:text-foreground tracking-tight truncate" {deployment.deployer.baseDomain}
>
{deployment.deployer.baseDomain}
</a>
</p> </p>
))} ))}
</div> </div>
</div> </div>
<OverviewInfo label="Domain" icon={<GlobeIcon />}> {/* <OverviewInfo label="Domain" icon={<GlobeIcon />}>
{liveDomain ? ( {liveDomain ? (
<Tag type="positive" size="xs" leftIcon={<CheckRoundFilledIcon />}> <Tag type="positive" size="xs" leftIcon={<CheckRoundFilledIcon />}>
Connected Connected
@ -174,7 +186,7 @@ const OverviewTabPanel = () => {
</Button> </Button>
</div> </div>
)} )}
</OverviewInfo> </OverviewInfo> */}
{project.deployments.length !== 0 ? ( {project.deployments.length !== 0 ? (
<> <>
{/* SOURCE */} {/* SOURCE */}
@ -193,11 +205,9 @@ const OverviewTabPanel = () => {
project.deployments.length > 0 && project.deployments.length > 0 &&
project.deployments.map((deployment) => ( project.deployments.map((deployment) => (
<div className="flex gap-2 items-center"> <div className="flex gap-2 items-center">
<Link <Link to={deployment.applicationDeploymentRecordData.url}>
to={`https://${project.name.toLowerCase()}.${deployment.deployer.baseDomain}`}
>
<span className="text-controls-primary dark:text-foreground group hover:border-controls-primary transition-colors border-b border-b-transparent flex gap-2 items-center text-sm tracking-tight"> <span className="text-controls-primary dark:text-foreground group hover:border-controls-primary transition-colors border-b border-b-transparent flex gap-2 items-center text-sm tracking-tight">
{`https://${project.name.toLowerCase()}.${deployment.deployer.baseDomain}`} {deployment.applicationDeploymentRecordData.url}
<LinkIcon className="group-hover:rotate-45 transition-transform" /> <LinkIcon className="group-hover:rotate-45 transition-transform" />
</span> </span>
</Link> </Link>

View File

@ -60,31 +60,39 @@ const Domains = () => {
return ( return (
<ProjectSettingContainer <ProjectSettingContainer
headingText="Domains" headingText="Domains"
button={ {...(!project.auctionId && {
<Button button: (
as="a" <Button
href="add" as="a"
variant="secondary" href="add"
leftIcon={<PlusIcon />} variant="secondary"
size="md" leftIcon={<PlusIcon />}
> size="md"
Add domain >
</Button> Add domain
} </Button>
> ),
{domains.map((domain) => {
return (
<DomainCard
domains={domains}
domain={domain}
key={domain.id}
// TODO: Use github API for getting linked repository
branches={branches}
project={project}
onUpdate={fetchDomains}
/>
);
})} })}
>
{project.auctionId ? (
<p className="text-gray-500">
Custom domains not supported for auction driven deployments.
</p>
) : (
domains.map((domain) => {
return (
<DomainCard
domains={domains}
domain={domain}
key={domain.id}
// TODO: Use github API for getting linked repository
branches={branches}
project={project}
onUpdate={fetchDomains}
/>
);
})
)}
</ProjectSettingContainer> </ProjectSettingContainer>
); );
}; };

View File

@ -7,6 +7,8 @@ import { InlineNotification } from 'components/shared/InlineNotification';
import { ArrowRightCircleIcon } from 'components/shared/CustomIcon'; import { ArrowRightCircleIcon } from 'components/shared/CustomIcon';
import { ProjectSettingContainer } from 'components/projects/project/settings/ProjectSettingContainer'; import { ProjectSettingContainer } from 'components/projects/project/settings/ProjectSettingContainer';
import { useToast } from 'components/shared/Toast'; import { useToast } from 'components/shared/Toast';
import { useEffect, useState } from 'react';
import { DNSRecordAttributes } from 'gql-client';
const Config = () => { const Config = () => {
const { id, orgSlug } = useParams(); const { id, orgSlug } = useParams();
@ -16,6 +18,8 @@ const Config = () => {
const primaryDomainName = searchParams.get('name'); const primaryDomainName = searchParams.get('name');
const { toast, dismiss } = useToast(); const { toast, dismiss } = useToast();
const [dnsRecord, setDnsRecord] = useState<DNSRecordAttributes | null>(null);
const handleSubmitDomain = async () => { const handleSubmitDomain = async () => {
if (primaryDomainName === null) { if (primaryDomainName === null) {
toast({ toast({
@ -59,51 +63,80 @@ const Config = () => {
} }
}; };
useEffect(() => {
const fetchDNSData = async () => {
if (id === undefined) {
toast({
id: 'domain_cannot_find_project',
title: 'Cannot find project',
variant: 'error',
onDismiss: dismiss,
});
return;
}
const dnsRecordResponse = await client.getLatestDNSRecordByProjectId(id);
setDnsRecord(dnsRecordResponse.latestDNSRecord);
};
fetchDNSData();
}, [id, client]);
// TODO: Figure out DNS Provider if possible and update appropriatly // TODO: Figure out DNS Provider if possible and update appropriatly
return ( return (
<ProjectSettingContainer headingText="Setup domain name"> <ProjectSettingContainer headingText="Setup domain name">
<p className="text-blue-gray-500"> {dnsRecord ? (
Add the following records to your domain. <>
</p> <p className="text-blue-gray-500">
Add the following records to your domain.
</p>
<Table> <Table>
<Table.Header> <Table.Header>
<Table.Row> <Table.Row>
<Table.ColumnHeaderCell>Type</Table.ColumnHeaderCell> <Table.ColumnHeaderCell>Type</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>Host</Table.ColumnHeaderCell> <Table.ColumnHeaderCell>Host</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>Value</Table.ColumnHeaderCell> <Table.ColumnHeaderCell>Value</Table.ColumnHeaderCell>
</Table.Row> </Table.Row>
</Table.Header> </Table.Header>
<Table.Body> <Table.Body>
<Table.Row> <Table.Row>
<Table.RowHeaderCell>A</Table.RowHeaderCell> <Table.RowHeaderCell>
<Table.Cell>@</Table.Cell> {dnsRecord.resourceType}
<Table.Cell>IP.OF.THE.SP</Table.Cell> </Table.RowHeaderCell>
</Table.Row> <Table.Cell>@</Table.Cell>
<Table.Cell>
<p className={!dnsRecord.value ? 'text-red-500' : ''}>
{dnsRecord.value ?? 'Not available'}
</p>
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
<Table.Row> {dnsRecord?.value && (
<Table.RowHeaderCell>CNAME</Table.RowHeaderCell> <InlineNotification
<Table.Cell>subdomain</Table.Cell> variant="info"
<Table.Cell>domain.of.the.sp</Table.Cell> title={`It can take up to 48 hours for these updates to reflect
</Table.Row> globally.`}
</Table.Body> />
</Table> )}
<Button
<InlineNotification className="w-fit"
variant="info" disabled={!dnsRecord?.value}
title={`It can take up to 48 hours for these updates to reflect onClick={handleSubmitDomain}
globally.`} variant="primary"
/> shape="default"
<Button rightIcon={<ArrowRightCircleIcon />}
className="w-fit" >
onClick={handleSubmitDomain} FINISH
variant="primary" </Button>
shape="default" </>
rightIcon={<ArrowRightCircleIcon />} ) : (
> <p className={'text-red-500'}>DNS record data not available</p>
FINISH )}
</Button>
</ProjectSettingContainer> </ProjectSettingContainer>
); );
}; };

View File

@ -12,6 +12,7 @@ import {
Domain, Domain,
Environment, Environment,
Permission, Permission,
AppDeploymentRecordAttributes,
} from 'gql-client'; } from 'gql-client';
export const user: User = { export const user: User = {
@ -111,6 +112,7 @@ export const deployment0: Deployment = {
}, },
applicationDeploymentRequestId: applicationDeploymentRequestId:
'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize', 'bafyreiaycvq6imoppnpwdve4smj6t6ql5svt5zl3x6rimu4qwyzgjorize',
applicationDeploymentRecordData: {} as AppDeploymentRecordAttributes,
}; };
export const project: Project = { export const project: Project = {

View File

@ -453,4 +453,15 @@ export class GQLClient {
return data.verifyTx; return data.verifyTx;
} }
async getLatestDNSRecordByProjectId(projectId: string): Promise<types.GetLatestDNSDataResponse> {
const { data } = await this.client.query({
query: queries.getLatestDNSRecordByProjectId,
variables: {
projectId,
},
});
return data;
}
} }

View File

@ -57,6 +57,9 @@ query ($projectId: String!) {
commitHash commitHash
createdAt createdAt
environment environment
applicationDeploymentRecordData {
url
}
deployer { deployer {
baseDomain baseDomain
} }
@ -112,6 +115,9 @@ query ($organizationSlug: String!) {
commitMessage commitMessage
createdAt createdAt
environment environment
applicationDeploymentRecordData {
url
}
domain { domain {
status status
branch branch
@ -343,3 +349,15 @@ query ($txHash: String!, $amount: String!, $senderAddress: String!) {
verifyTx(txHash: $txHash, amount: $amount, senderAddress: $senderAddress) verifyTx(txHash: $txHash, amount: $amount, senderAddress: $senderAddress)
} }
`; `;
export const getLatestDNSRecordByProjectId = gql`
query($projectId: String!) {
latestDNSRecord(projectId: $projectId) {
name
value
request
resourceType
version
}
}
`;

View File

@ -108,6 +108,7 @@ export type Deployment = {
environment: Environment; environment: Environment;
isCurrent: boolean; isCurrent: boolean;
baseDomain?: string; baseDomain?: string;
applicationDeploymentRecordData: AppDeploymentRecordAttributes;
status: DeploymentStatus; status: DeploymentStatus;
createdBy: User; createdBy: User;
createdAt: string; createdAt: string;
@ -376,3 +377,28 @@ export type AuctionParams = {
maxPrice: string; maxPrice: string;
numProviders: number; numProviders: number;
}; };
export type DNSRecordAttributes = {
name: string;
value: string;
request: string;
resourceType: string;
version: string;
}
export type GetLatestDNSDataResponse = {
latestDNSRecord: DNSRecordAttributes | null
}
export interface AppDeploymentRecordAttributes {
application: string;
auction: string;
deployer: string;
dns: string;
meta: string;
name: string;
request: string;
type: string;
url: string;
version: string;
}